206. Reverse Linked List
grandyang: http://www.cnblogs.com/grandyang/p/4478820.html
方法1: iterative
易错点:
- 交接节点的顺序
- 查空的条件是head -> next不为空。因为我们操作的范围是prev, head, head -> next, head -> next -> next
- 一刷的方法没有用到四个节点,
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (!head) return nullptr;
ListNode* prev = nullptr;
while (head->next != nullptr){
ListNode* t = head->next;
head->next = prev;
prev = head;
head = t;
}
head->next = prev;
return head;
}
};
// 二刷
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (!head) return nullptr;
ListNode* prev = new ListNode(-1);
prev -> next = head;
while (head -> next) {
ListNode* tmp = head -> next;
head -> next = tmp -> next;
tmp -> next = prev -> next;
prev -> next = tmp;
}
return prev -> next;
}
};
方法2: recursion
思路:
用递归的办法,首先我们要找到递归的终点。注意这里选取最后一个节点而不是null为终点是因为我们需要返回的是一个新链的head,而这个newHead会被一直向上返回,作为整体函数的返回值。但这里还要做多一步防守(!head)是因为有[] 的test case。那么每一步要做的就是:1. 将head -> next -> next = head, 2. head -> next = nullptr. 这样来看整个向前递归的目的首先是为了找到newHead,然后将head和head->next->next连接逆转。利用递归的好处就是,从后往前的切链,在返回后自然保留了prev这一个节点。
易错点
- 注意(!head)
- 在递归中head -> next = nullptr:这里注意要切空(为什么?)
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (!head || !head -> next) return head;
ListNode* newHead = reverseList(head -> next);
head -> next -> next = head;
head -> next = nullptr;
return newHead;
}
};