-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRotate_Doubly_Linked_List.cpp
123 lines (101 loc) · 2.23 KB
/
Rotate_Doubly_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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
//{ Driver Code Starts
//Initial Template for C++
#include<bits/stdc++.h>
using namespace std;
typedef struct node
{
int data;
struct node*next,*prev;
node(int x){
data = x;
next = NULL;
prev = NULL;
}
} Node;
// } Driver Code Ends
//User function Template for C++
/*
typedef struct node
{
int data;
struct node*next,*prev;
node(int x){
data = x;
next = NULL;
prev = NULL;
}
} Node;
*/
class Solution {
public:
Node *rotateDLL(Node *start,int p)
{
if (start == NULL || p == 0) return start;
int n = 1;
Node* last = start;
while(last->next != NULL)
{
n++;
last = last->next;
}
Node* curr = start;
p = p % n;
if(p == 0) return start;
for(int i = 1; i < p; i++) curr = curr->next;
Node* newHead = curr->next;
curr->next = NULL;
newHead->prev = NULL;
last->next = start;
start->prev = last;
return newHead;
}
};
//{ Driver Code Starts.
int main()
{
int t;
cin>>t;
while(t--)
{
int n,p;
cin>>n>>p;
struct node*start = NULL;
struct node* cur = NULL;
struct node* ptr = NULL;
for(int i=0;i<n;i++)
{
int a;
cin>>a;
ptr=new node(a);
ptr->data=a;
ptr->next=NULL;
ptr->prev=NULL;
if(start==NULL)
{
start=ptr;
cur=ptr;
}
else
{
cur->next=ptr;
ptr->prev=cur;
cur=ptr;
}
}
Solution obj;
struct node*str=obj.rotateDLL(start,p);
while(1)
{
cout<<str->data<<" ";
if(str->next==NULL)break;
str=str->next;
}
// while(str!=NULL)
// {
// cout<<str->data<<" ";
// str=str->prev;
// }
cout<< "\n";
}
}
// } Driver Code Ends