[InterviewBit] Reverse Link List II

Reverse Link List II

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
ListNode* nThNode(ListNode* A, int n) {
ListNode* runner = A;
while(n--) runner = runner->next;
return runner;
}
ListNode* reverse(ListNode* A) {
ListNode* dummy = new ListNode(-1);
while(A) {
ListNode* nxt = A->next;
A->next = dummy->next;
dummy->next = A;
A = nxt;

}

return dummy->next;
}
ListNode* Solution::reverseBetween(ListNode* A, int B, int C) {
if(B == C) return A;
ListNode* dummy = new ListNode(-1);
dummy->next = A;
ListNode *lb = nThNode(dummy, B-1), *right = nThNode(dummy, C);
ListNode *left = lb->next, *rb = right->next;
lb->next = right->next = NULL;
lb->next = reverse(left);
ListNode* runner = dummy;
while(runner->next) runner = runner->next;
runner->next = rb;

return dummy->next;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/15/PS/interviewbit/reverse-link-list-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.