-
Notifications
You must be signed in to change notification settings - Fork 232
/
Copy pathRotate_LinkList.cpp
79 lines (69 loc) · 1.68 KB
/
Rotate_LinkList.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// Problem: Given the head of a linked list, rotate the list to the right by k places.
// Input:
// head = [1,2,3,4,5]
// k = 2
// Output:
// head = [4,5,1,2,3]
//code
#include<bits/stdc++.h>
using namespace std;
class node {
public:
int num;
node* next;
node(int a) {
num = a;
next = NULL;
}
};
//utility function to insert node at the end of the list
void insertNode(node* &head,int val) {
node* newNode = new node(val);
if(head == NULL) {
head = newNode;
return;
}
node* temp = head;
while(temp->next != NULL) temp = temp->next;
temp->next = newNode;
return;
}
//utility function to rotate list by k times
node* rotateRight(node* head,int k) {
if(head == NULL||head->next == NULL) return head;
for(int i=0;i<k;i++) {
node* temp = head;
while(temp->next->next != NULL) temp = temp->next;
node* end = temp->next;
temp->next = NULL;
end->next = head;
head = end;
}
return head;
}
//utility function to print list
void printList(node* head) {
while(head->next != NULL) {
cout<<head->num<<"->";
head = head->next;
}
cout<<head->num<<endl;
return;
}
int main() {
node* head = NULL;
//inserting Node
insertNode(head,1);
insertNode(head,2);
insertNode(head,3);
insertNode(head,4);
insertNode(head,5);
cout<<"Original list: ";
printList(head);
int k = 2;
node* newHead = rotateRight(head,k);//calling function for rotating right of
the nodes by k times
cout<<"After "<<k<<" iterations: ";
printList(newHead);//list after rotating nodes
return 0;
}