-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReversing_Doubly_linklist.cpp
127 lines (109 loc) · 2.13 KB
/
Reversing_Doubly_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
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
124
125
126
127
#include <iostream>
using namespace std;
class node{
public:
node *next;
node *priv;
int val;
node(int val);
};
node::node(int val)
{
this->val = val;
next = priv = NULL;
}
class List{
node *current, *head;
int length;
public:
void append(int val);
List();
void print();
node* get_last();
void reverse();
};
List::List()
{
head = current = NULL;
length = 0;
}
node* List::get_last()
{
current = head;
node* last = head;
for(int i = 1 ; i < length; i++)
{
last = last->next;
}
return last;
}
void List::reverse()
{
if (length <= 1)return;
current = get_last();
head = current; // last node will be our head
node* temp = current->priv;
while(true)
{
current->next = temp;
if(temp->priv == NULL)
{
temp->priv = current;
temp->next = NULL;
head->priv = NULL;
return; // done return
}
temp = temp->priv;
temp->next->priv = current;
current = temp->next;
}
}
void List::print()
{
current = head;
std::cout << "[ ";
while(current != NULL)
{
if(current->next == NULL) // it will look like python list
std::cout <<current->val << " ]";
else
std::cout << current->val << ", ";
current = current->next;
}
std::cout << std::endl;
}
void List::append(int val)
{
if(head == NULL)
{
head = new node(val);
length++;
current = head;
return;
}
current = get_last();
node* n = new node(val);
length++;
current->next = n;
n->priv = current;
current = current->next;
}
int main(){
List l;
for(int i = 1; i <= 10; i++)
{
if(i == 5)
continue;
l.append(i);
}
l.append(20);
l.append(21);
l.append(22);
l.print();
l.reverse();
l.print();
l.reverse(); // again reversing to get the ist list
l.print();
std::cout << std::endl;
return 0;
}