[AlgoExpert] Shift Linked List

Shift Linked List

  • Time : O(n)
  • Space : O(1)
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
41
42
43
44
45
46
47
48
using namespace std;

class LinkedList {
public:
int value;
LinkedList *next;

LinkedList(int value) {
this->value = value;
next = nullptr;
}
};

int size(LinkedList* head) {
int count = 0;
LinkedList* tmp = head;

while(tmp != nullptr) {
count++;
tmp = tmp->next;
}
return count;
}

LinkedList *shiftLinkedList(LinkedList *head, int k) {
int sz = size(head);
if(k < 0) {
k = ((k / sz) - 1) * -sz + k;
}
k = k % sz;
if(k == 0) return head;

LinkedList* faster = head;
for(int i = 0; i < k; i++)
faster = faster->next;

LinkedList* oldHead = head;

while(faster->next != nullptr) {
faster = faster->next;
oldHead = oldHead->next;
}
faster->next = head;
head = oldHead->next;
oldHead->next = nullptr;
return head;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/28/PS/AlgoExpert/shift-linked-list/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.