[InterviewBit] Rotate List

Rotate 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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
ListNode* Solution::rotateRight(ListNode* A, int B) {
ListNode* runner = A;
for(int i = 0; i < B; i++) {
runner = runner->next;
if(!runner) runner = A;
}
if(runner == A) return A;
ListNode* head = A;
while(runner->next) {
runner = runner->next;
head = head->next;
}
runner->next = A;
ListNode* res = head->next;
head->next = NULL;
return res;
}

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