-
Notifications
You must be signed in to change notification settings - Fork 0
/
rotate_doubly.cpp
91 lines (76 loc) · 1.09 KB
/
rotate_doubly.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
90
91
//rotate a doubly linked list in anti-clockwise n times;
#include <bits/stdc++.h>
using namespace std;
class node{
public:
int data;
node *prev;
node *next;
node(int x)
{
data = x;
prev = NULL;
next = NULL;
}
};
node *head = NULL;
node *tail = NULL;
void insert(int x)
{
node *temp = new node(x);
if(head == NULL)
{
head = temp;
tail = temp;
return;
}
temp->prev = tail;
tail->next = temp;
tail = temp;
}
void rotate_nodes(int p)
{
if(p == 0) return;
node *last = head;
node *ptr = head;
while(last->next != NULL)
{
last = last->next;
}
while(p > 0 && ptr != NULL)
{
ptr = ptr->next;
p--;
}
if(ptr == NULL) return;
head->prev = last;
last->next = head;
ptr->prev->next = NULL;
ptr->prev = NULL;
head = ptr;
}
void display(node *head)
{
while(head != NULL)
{
cout << head->data << " ";
head = head->next;
}
cout << "\n";
}
int main()
{
int n,x;
cin >> n;
for(int i = 0; i < n; i++)
{
cin >> x;
insert(x);
}
cout << "Enter number of nodes to be rotated: ";
cin >> x;
rotate_nodes(x);
cout << "Updated list: ";
display(head);
return 0;
}