forked from akibzaman/Beginners-Data-Structure
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdoublyLinkedList.cpp
140 lines (120 loc) · 2.59 KB
/
doublyLinkedList.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
128
129
130
131
132
133
134
135
136
137
138
139
140
#include <bits/stdc++.h>
using namespace std;
class doublyNode{
public:
int val;
doublyNode* prev;
doublyNode* next;
doublyNode(int val){
this->val=val;
prev = NULL;
next = NULL;
}
};
void insertAtTail(doublyNode *&head, int val)
{
doublyNode *newNode = new doublyNode(val);
if (head == NULL)
{
head = newNode;
return;
}
doublyNode *temp = head;
while (temp->next != NULL)
{
temp = temp->next;
}
temp->next = newNode;
newNode->prev=temp;
}
void insertAtHead(doublyNode* &head, int val){
// s1: newNode creation
doublyNode *newNode = new doublyNode(val);
//s2: Update of head->prev
head->prev = newNode;
// s3: Update of newNode->Next
newNode->next = head;
// s4: Update of head
head = newNode;
}
void display(doublyNode* n)
{
while (n != NULL)
{
cout << n-> val ;
if (n->next != NULL)
cout << " ---> ";
n = n->next;
}
cout << endl
<< endl;
}
void displayReverse(doublyNode* &head)
{
doublyNode* temp = head;
while(temp->next!=NULL){
temp=temp->next;
}
while (temp != NULL)
{
cout << temp-> val ;
if (temp->prev != NULL)
cout << " ---> ";
temp = temp->prev;
}
cout << endl
<< endl;
}
int countLength(doublyNode *&head)
{
int count = 0;
doublyNode *temp = head;
while (temp != NULL)
{
count++;
temp = temp->next;
}
return count;
}
int main()
{
doublyNode *head = NULL;
int value, position;
// Choice 1: Insertion at Head
// Choice 2: Insertion at Tail
cout << "Choice 1: Insertion at Head" << endl
<< "Choice 2: Insertion at Tail" << endl
<< "Choice 3: Reverse Print" << endl
<< "Choice 0: Exit" << endl
<< endl;
cout << "Next Choice: ";
int choice;
cin >> choice;
while (choice != 0)
{
switch (choice)
{
case 1:
cout << "Enter the Value: ";
cin >> value;
insertAtHead(head, value);
break;
case 2:
cout << "Enter the Value: ";
cin >> value;
insertAtTail(head, value);
break;
case 3:
displayReverse(head);
break;
default:
break;
}
cout << "Next Choice: ";
cin >> choice;
}
cout << endl << "Doubly Linked List: ";
display(head);
cout << "Length of the Doubly Linked List: " << countLength(head) << endl;
return 0;
}