File tree Expand file tree Collapse file tree 1 file changed +17
-45
lines changed
Data Structures/Linked Lists Expand file tree Collapse file tree 1 file changed +17
-45
lines changed Original file line number Diff line number Diff line change 1
1
#include < bits/stdc++.h>
2
2
3
+ /*
4
+ Given a doubly linked list of n elements. The task is to reverse the doubly linked list.
5
+
6
+ Example:
7
+ Input: LinkedList: 3 <--> 4 <--> 5
8
+ Output: 5 4 3
9
+ */
10
+
3
11
using namespace std ;
4
12
5
13
struct Node
@@ -24,8 +32,6 @@ Node *newNode(int data)
24
32
}
25
33
26
34
27
-
28
-
29
35
void displayList (Node *head)
30
36
{
31
37
while (head->next )
@@ -39,47 +45,16 @@ void displayList(Node *head)
39
45
40
46
}
41
47
48
+ // main function for reversing the doubly linked list
42
49
43
- int getLength (Node * head)
44
- {
45
- Node *temp=head;
46
-
47
- int count=0 ;
48
- while (temp->next !=head)
49
- {
50
- count++;
51
- temp=temp->next ;
52
- }
53
- return count+1 ;
54
- }
55
-
56
-
57
-
58
-
59
- bool verify (Node* head)
60
- {
61
- int fl=0 ;
62
- int bl=0 ;
63
-
64
- Node *temp=head;
65
-
66
- while (temp->next )
67
- {
68
- temp=temp->next ;
69
- fl++;
70
- }
71
-
72
- while (temp->prev )
73
- {
74
- temp=temp->prev ;
75
- bl++;
76
- }
77
-
78
- return fl==bl;
79
- }
80
-
50
+ /*
51
+ Approch:
52
+ Simply just keep track of the previous node
53
+ and the next node.
81
54
82
- // main function for reversing the doubly linked list
55
+ Almost similar to the singly linked list you have an extra pointer
56
+ as prev to take care of
57
+ */
83
58
Node* reverseDLL (Node * head)
84
59
{
85
60
Node* temp = NULL ;
@@ -124,11 +99,8 @@ int main() {
124
99
head=reverseDLL (head);
125
100
126
101
127
- if (verify (head))
128
102
displayList (head);
129
- else
130
- cout<<" Your pointers are not correctly connected" ;
131
-
103
+
132
104
cout<<endl;
133
105
}
134
106
return 0 ;
You can’t perform that action at this time.
0 commit comments