Reverse a singly linked list.
Input : Head of following linked list
1->2->3->4->NULL
Output : Linked list should be changed to,
4->3->2->1->NULL
Input : Head of following linked list
1->2->3->4->5->NULL
Output : Linked list should be changed to,
5->4->3->2->1->NULL
Input : NULL
Output : NULL
Input : 1->NULL
Output : 1->NULL
经典的不能再经典的题目,要背下来才能快速写出,要是从头自己想的话绝对会跪。
主要有两种方式,第一种是递推,第二种是递归。
递推解法:
有三个pointer:cur, prev, next。cur, next指代在某一轮开始的时候要“反转”的节点,prev是上一个节点(第一个节点的prev为NULL)每次迭代:next记录下一个节点,cur节点反转,cur和prev依次后移。
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* next = head, *cur = head, *prev = NULL;
while(cur){
next = cur -> next;
cur->next = prev;
prev = cur;
cur = next;
}
return prev;
}
};
递归解法:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (!head || !(head -> next)) return head;
ListNode* node = reverseList(head -> next);
head -> next -> next = head;
head -> next = NULL;
return node;
}
};
递归解法的一个困难就是如何记录最后的指针,这种解法挺聪明的,要背下来写熟练。

本文详细介绍了如何使用递推和递归方法实现链表的反转。通过具体的代码示例,展示了不同方法的操作步骤,并提供了完整的解决方案。
254

被折叠的 条评论
为什么被折叠?



