-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreverse_doubly_linked_list.cpp
72 lines (65 loc) · 1.12 KB
/
reverse_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
#include <bits/stdc++.h>
using namespace std;
class Node
{
public:
int val;
Node *next;
Node *prev;
Node(int val)
{
this->val = val;
this->next = NULL;
this->prev = NULL;
}
};
void print_reverse(Node *head)
{
Node *tmp = head;
if (tmp == NULL)
return;
print_reverse(tmp->next);
cout << tmp->val << " ";
}
void print(Node *head)
{
Node *tmp = head;
while (tmp != NULL)
{
cout << tmp->val << " ";
tmp = tmp->next;
}
cout << endl;
}
void reverse(Node *head, Node *tail)
{
Node *i = head;
Node *j = tail;
while (i != j && i->next != j)
{
swap(i->val, j->val);
i = i->next;
j = j->prev;
}
}
int main()
{
Node *head = new Node(10);
Node *a = new Node(20);
Node *b = new Node(30);
Node *c = new Node(40);
Node *d = new Node(50);
Node *tail = d;
head->next = a;
a->prev = head;
a->next = b;
b->prev = a;
b->next = c;
c->prev = b;
c->next = d;
d->prev = c;
// print_reverse(head);
reverse(head, tail);
print(head);
return 0;
}