0%

206. reverse-linked-list

反转链表

题目

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

示例1:

输入: head = [1,2,3,4,5]
输出:[5,4,3,2,1]

思路

双指针
只需要改变当前链表节点的指向指向前一个节点即可。创建一个temp保存之前的下一个节点即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* temp;
ListNode* pre = NULL;
ListNode* cur = head;
while(cur){
temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
return pre;
}
};