-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathRotate-Node.cpp
52 lines (39 loc) · 1.15 KB
/
Rotate-Node.cpp
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
49
50
51
52
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
ListNode *temp = head, *ptr = head;
// if list is empty return NULL
if(head == NULL)
return NULL;
// if list contain 1 node return NULL
if(head -> next == NULL)
return head;
int cnt = 1;
// counting nodes in list
while(temp->next != NULL)
{
temp = temp -> next;
cnt++;
}
// mod of k with cnt to find the minimum no of rotations.
k = k % cnt;
while(k--)
{
while(temp->next != NULL)
temp = temp -> next;
temp -> next = head; //making it a circular linked list
// making last node the new head
head = temp;
ptr = temp;
// moving list values one by one
while(temp -> next != head)
{
temp = temp -> next;
}
// adding NULL at end of list
temp -> next = NULL;
temp = ptr;
}
return head;
}
};