Leetcode: Reverse Linked List
阿新 • • 發佈:2018-11-19
linkedlist,iterative seems much easier than recursive
- Reverse Linked List
https://leetcode.com/problems/reverse-linked-list/description/
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverseList(ListNode* head) { ListNode* next; ListNode* pre = NULL; ListNode* cur = head; while(cur) { next = cur->next; cur->next = pre; pre = cur; cur = next; } return pre; } };
每次寫連結串列,很容易在賦值中凌亂,
比如上面的:
next = cur->next; //把cur->next(也就是下一個node)賦值給next
cur->next = pre; //把pre(也就是上一個node)賦值給cur->next,也就是改變了cur->next的指向,從以前的next指向了pre
所以:
如果討論賦值的話,就是從右往左
如果討論指標指向的話,就是從左往右
或者:
cur->next在右邊就是指的是下一個節點
cur->next在左邊就是cur的next pointer
一般都是先把原來的linked node存下來,然後再改變指向,就把原來的link break了
pre = cur; //把cur賦值給pre,也就是pre移到下一個節點
cur = next; //把next賦值給cur,也就是把cur移到下一個節點
比如下面的:
newhead = reverseList(head->next);// newhead就是原list的tail
head->next->next = head;//head->next其實是reversed list的tail,tail->next指向原來的head,原來的head就變成了新list的tail
head->next = NULL; //最後指向nULL
ListNode* newhead; if(head == NULL || head->next == NULL) { return head; } newhead = reverseList(head->next); head->next->next = head; head->next = NULL; return newhead;