(1) move pointer to position m.
(2) reverse sublist from m to n. Note, the first node in the sublist will be the tail in the reversed list so we just need to move the node behind it to the head of the sublist by insertion. Also note prev->next will always be the head of the sublist no matter it is done with the reverse.
I made several mistakes here.
(1) In line 23, I was trying to link p->next to cur. This is true for the first round but it is wrong since then because cur is moved forward by inserting a tail node before it. Instead, we are inserting tail node before head which is actually prev->next.
(2) I was trying to move prev to next. Note, prev is always fixed here as in the sublist, we try to insert tail node before head which is right after prev.
(3) I was trying to compute n after line 17. Note after line 17, m has become 0.
1: /**
2: * Definition for singly-linked list.
3: * struct ListNode {
4: * int val;
5: * ListNode *next;
6: * ListNode(int x) : val(x), next(NULL) {}
7: * };
8: */
9: class Solution {
10: public:
11: ListNode* reverseBetween(ListNode* head, int m, int n) {
12: if (m == n) return head;
13: n -= m;
14: ListNode *dummy = new ListNode(-1);
15: dummy->next = head;
16: ListNode *prev = dummy;
17: while (--m) prev = prev->next;
18: ListNode *cur = prev->next;
19: // we don't need to move prev.
20: while (n--) {
21: ListNode *p = cur->next;
22: cur->next = p->next;
23: p->next = prev->next;
24: prev->next = p;
25: }
26: return dummy->next;
27: }
28: };
No comments:
Post a Comment