Reverse Whole List

Reverse Whole List

题目描述:

给定链表的头结点,将其全部逆序后返回新链表的头结点。

例子:

具体的描述可以看LeetCode206

解题思路:

链表中的基本题;主要的难点在于要保存下一个节点用于下次遍历;另外我们用pre=NULL这个操作可以少定义一个变量。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (!head) return head;
ListNode* pre = NULL;
ListNode* cur = head;
while(cur){
ListNode* next = cur->next;
# 保存下一个节点
cur->next = pre;
# 重新指向指针,此处pre定义为NULL,一举两得
pre = cur;
cur = next;
# 更改pre和cur继续遍历
}
return pre;
}
};