-
Notifications
You must be signed in to change notification settings - Fork 344
/
Copy pathClockwise_rotation _of_Linked_List.cpp
89 lines (83 loc) · 1.53 KB
/
Clockwise_rotation _of_Linked_List.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
80
81
82
83
84
85
86
87
88
89
#include<bits/stdc++.h>
using namespace std;
class Node{
public:
int data;
Node *next;
Node(int data)
{
this->data=data;
next=NULL;
}
};
Node* add(Node *head,int data)
{
Node* temp=new Node(data);
if(head==NULL)
{
head=temp;
}
else{
Node *trav=head;
while(trav->next!=NULL)
{
trav=trav->next;
}
trav->next=temp;
}
return head;
}
Node* rotateRight(Node* head, int k) {
if (!head || !head->next || k == 0)
return head;
Node *cur = head;
int len = 1;
while (cur->next)
{
len++; //count the length of LinkedList.
cur = cur->next;
}
cur->next = head; //connect last node to first to make circular.
k = len - k % len; //to find actual number of rotation.
while (k--)
{
cur = cur->next;
}
head = cur->next;
cur->next = nullptr;
return head;
}
void print(Node* head)
{
if(head==NULL)
{
cout<<"no data in linkedlist";
}
{
Node *temp=head;
while(temp!=NULL)
{
cout<<temp->data<<"-->";
temp=temp->next;
}
}
cout<<"NULL"<<endl;
}
int main()
{
Node *head=NULL;
int n,k;
cout<<"enter the size of linkedlist and k :";
cin>>n>>k;
for(int i=0; i<n; i++)
{
int element;
cin>>element;
head=add(head,element);
}
print(head);
cout<<"after clockwise rotation"<<endl;
head=rotateRight(head,k);
print(head);
return 0;
}