您的位置:首页 > 其它

LC 206 Reverse a singly linked list.

2018-03-13 15:56 260 查看
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

经典的不能再经典的题目,要背下来才能快速写出,要是从头自己想的话绝对会跪。
Geeksforgeeks解析

主要有两种方式,第一种是递推,第二种是递归。
递推解法:
有三个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;
}
};     递归解法的一个困难就是如何记录最后的指针,这种解法挺聪明的,要背下来写熟练。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  经典算法