-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path37-Rotate Linked List
43 lines (36 loc) · 957 Bytes
/
37-Rotate Linked List
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
/**
* Definition for singly-linked list.
* class Node {
* public:
* int data;
* Node *next;
* Node() : data(0), next(nullptr) {}
* Node(int x) : data(x), next(nullptr) {}
* Node(int x, Node *next) : data(x), next(next) {}
* };
*/
Node *rotate(Node *head, int k) {
// Write your code here.
//Edge Cases
if(head==NULL || head->next==NULL || k==0){
return head;
}
//calculate the length while reaching to the end of LL
Node* curr=head;
int len=1;
while(curr->next && ++len){
curr=curr->next;
}
//Now you have the length of the linked list and you are at the last node with curr pointer
//join the last node to the first node
curr->next=head;
k=k%len;
k=len-k;
while(k--){
curr=curr->next;
}
//Now you are one before from where we have to roate
head=curr->next;
curr->next=NULL;
return head;
}