forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DoublyLinkedList.cpp
121 lines (109 loc) · 2.64 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
/* This program implements Doubly Linked List for creation,insertion and Reversing the Linked List
A Doubly Linked List (DLL) contains an extra pointer, typically called previous pointer, together with next pointer and data which are there in singly linked list.
@author: GudlaArunKumar
@created: 30/06/2020
*/
#include <iostream>
using namespace std;
struct Node{ // Created structure Node which contains Data, previous and Next pointer
struct Node *prev;
int data;
struct Node *next;
}*first=NULL; //Declared struct object as First globally
void create(int arr[],int n){ //Creation of Doubly Linked List
struct Node *tmp,*last;
first=new Node;
first->data=arr[0];
first->prev=first->next=NULL;
last=first;
for(int i=1;i<n;i++)
{
tmp = new Node;
tmp->data = arr[i];
tmp->next=last->next;
tmp->prev=last;
last->next=tmp;
last=tmp;
}
}
void display(struct Node *p) //Displaying the elements in Doubly Linked List while travsersing through Next pointer only
{
cout <<"Elements in doubly Linked list are:" << endl;
while(p!=NULL)
{
cout << p->data << " ";
p=p->next;
}
cout << endl;
}
int Length(struct Node *p) //Calculates Length of DLL
{
int count =0;
while(p!=NULL)
{
count++;
p=p->next;
}
return count;
}
void Insert(int pos,int x) //Insertion operation takes place with repect to position given by User
{
struct Node *tmp,*p=first;
if(pos==0)
{
tmp = new Node;
tmp->data=x;
tmp->next=first;
tmp->prev=NULL;
first->prev=tmp;
first=tmp;
}
else
{
tmp = new Node;
tmp->data=x;
for(int i=0;i<pos-1;i++)
{
p=p->next;
}
tmp->next=p->next;
tmp->prev=p;
if(p->next)
{
p->next->prev=tmp;
}
p->next=tmp;
}
}
void ReverseList(struct Node *p) //Reversing the DLL by swapping Prev and Next Pointer of each Node
{
p=first;
struct Node *temp;
while(p!=NULL)
{
temp=p->prev;
p->prev=p->next;
p->next=temp;
p=p->prev;
if(p!=NULL && p->next==NULL)
{
first=p;
}
}
}
int main(){
int arr[7]={10,20,30,40,50,60,70};
int pos,element;
create(arr,7);
display(first); // Displaying DLL
cout << "Length of List is: " << Length(first) << endl;
cout << "Enter position and element to insert in the Linked List" << endl; //Data will be inserted at "Position+1" in Doubly Linked List
cin >> pos;
cin >> element;
Insert(pos,element);
display(first);
cout << "After Reversing the Linked List, ";
ReverseList(first);
display(first);
return 0;
}