Skip to content

Commit dc2ec8a

Browse files
Reverse Doubly Linked List
1 parent 9cc7070 commit dc2ec8a

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed

reverse_doubly_linked_list.cpp

+72
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
class Node
5+
{
6+
public:
7+
int val;
8+
Node *next;
9+
Node *prev;
10+
Node(int val)
11+
{
12+
this->val = val;
13+
this->next = NULL;
14+
this->prev = NULL;
15+
}
16+
};
17+
18+
void print_reverse(Node *head)
19+
{
20+
Node *tmp = head;
21+
if (tmp == NULL)
22+
return;
23+
print_reverse(tmp->next);
24+
cout << tmp->val << " ";
25+
}
26+
27+
void print(Node *head)
28+
{
29+
Node *tmp = head;
30+
while (tmp != NULL)
31+
{
32+
cout << tmp->val << " ";
33+
tmp = tmp->next;
34+
}
35+
cout << endl;
36+
}
37+
38+
void reverse(Node *head, Node *tail)
39+
{
40+
Node *i = head;
41+
Node *j = tail;
42+
while (i != j && i->next != j)
43+
{
44+
swap(i->val, j->val);
45+
i = i->next;
46+
j = j->prev;
47+
}
48+
}
49+
50+
int main()
51+
{
52+
Node *head = new Node(10);
53+
Node *a = new Node(20);
54+
Node *b = new Node(30);
55+
Node *c = new Node(40);
56+
Node *d = new Node(50);
57+
Node *tail = d;
58+
head->next = a;
59+
a->prev = head;
60+
a->next = b;
61+
b->prev = a;
62+
b->next = c;
63+
c->prev = b;
64+
c->next = d;
65+
d->prev = c;
66+
67+
// print_reverse(head);
68+
reverse(head, tail);
69+
print(head);
70+
71+
return 0;
72+
}

reverse_doubly_linked_list.exe

52.1 KB
Binary file not shown.

0 commit comments

Comments
 (0)