LC 206 Reverse a singly linked list.
2018-03-13 15:56
260 查看
Reverse a singly linked list.
经典的不能再经典的题目,要背下来才能快速写出,要是从头自己想的话绝对会跪。
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;
}
}; 递归解法的一个困难就是如何记录最后的指针,这种解法挺聪明的,要背下来写熟练。
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;
}
}; 递归解法的一个困难就是如何记录最后的指针,这种解法挺聪明的,要背下来写熟练。
相关文章推荐
- Leetcode 206 Reverse Linked List
- LeetCode 206:Reverse Linked List
- 【leetcode】【单链表】【206】Reverse Linked List
- 反转单向链表(reverse a singly linked list)
- leetcode: (206) Reverse Linked List
- LeetCode题解-206-Reverse Linked List Ⅰ
- leetcode206 Reverse Linked List
- 206 - Reverse Linked List
- leetcode-206 Reverse Linked List
- LeetCode_206 Reverse Linked List
- LeetCode 148: SortList, 206:Reverse linked list
- 两两反转单向链表 (reverse a singly linked list in pair ) [#22]
- 【leetcode】【单链表】【206】Reverse Linked List
- <LeetCode><Easy>206 ReverseLinkedList
- 206。Reverse Linked List
- [leetcode 206] Reverse Linked List
- 206、Reverse Linked List [Leetcode]
- LeetCode 206 -Reverse Linked List ( JAVA )
- leetcode 206 Reverse Linked List C++
- [Leetcode 206, Easy] Reverse Linked List