-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrotateLL.cpp
56 lines (44 loc) · 978 Bytes
/
rotateLL.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
53
54
55
56
//rotate the linked list
#include<bits/stdc++.h>
using namespace std;
class Node {
public :
int data;
Node* next;
Node(int data1 , Node* next1){
data = data1;
next = next1;
}
Node(int data1){
data = data1;
next = nullptr;
}
};
//function for nth node
Node* findNthNode(Node* temp , int k){
int cnt = 1;
while(temp != nullptr){
if(cnt == k) return temp;
cnt++;
temp = temp->next;
}
return temp;
};
//rotate function
Node* rotateLL(Node* head , int k){
if(head == nullptr || head->next == nullptr){
return head;
}
Node* tail = head;
int len = 1;
while(tail->next != nullptr){
tail = tail->next;
len++;
}
if(k%len == 0) return head;
k = k%len;
tail->next = head;
Node* newLastNode = findNthNode(head , len-k);
newLastNode->next = nullptr;
return head;
}