[InterviewBit] K reverse linked list

K reverse linked list

  • 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* cut(ListNode* A, int k) {
ListNode* runner = A;
for(int i = 0; i < k - 1; i++) runner = runner->next;
return runner;
}
ListNode* reverse(ListNode* A) {
ListNode* dummy = new ListNode(-1);
ListNode* runner = A;
while(runner) {
ListNode* next = runner->next;
runner->next = dummy->next;
dummy->next = runner;
runner = next;
}
return dummy->next;
}
ListNode* Solution::reverseList(ListNode* A, int B) {
ListNode* dummy = new ListNode(-1);
ListNode* tail = dummy;
ListNode* runner = A;
while(runner) {
ListNode* last = cut(runner, B);
ListNode* next = last->next;
last->next = NULL;
ListNode* rev = reverse(runner);
tail->next = rev;
tail = runner;
runner = next;
}
return dummy->next;
}

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