您的位置:首页 > 其它

206 - Reverse Linked List

2016-03-10 10:44 302 查看
Reverse a singly linked list.

click to show more hints.

Subscribe to see which companies asked this question
思路分析:
此题较容易。
我们可以设置一个新的指针newHead。初始化为NULL。
此时,迭代原始的链表。每一次把原始的链表的节点从头插入newHead中。
假定初始链表为:1->2->3->4->5
1. newhead->1->null

2. newhead->2->1->null

...

5 newhead->5->4->3->2->1->null

Then just return newhead->next.
#include "stdafx.h"
#include <iostream>

using namespace std;

struct ListNode 
{
	int val;
	ListNode *next;
	ListNode(int x) : val(x), next(NULL) {}
};

class Solution_206_ReverseLinkedList
{
public:
	ListNode* reverseList(ListNode* head) 
	{
		ListNode *newHead = new ListNode(0);

		while (head)
		{
			ListNode *tmp = head->next;
			newHead->next = head;
			head = head->next;
			newHead->next->next = tmp;
		}
		return newHead->next;
	}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: