-
Notifications
You must be signed in to change notification settings - Fork 0
/
DLL.cpp
146 lines (144 loc) · 2.36 KB
/
DLL.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
141
142
143
144
145
146
#include <iostream>
#define endl '\n'
using namespace std;
struct DLLNode
{
int data;
struct DLLNode *next;
struct DLLNode *prev;
};
void insert(DLLNode **head,int data,int pos)
{
struct DLLNode *p,*newNode;
newNode=new DLLNode;
if(!newNode)
{
cout<<"Memory allocation error\n";
return;
}
int k=1;
newNode->data=data;
p=*head;
if(pos==1)
{
newNode->next=*head;
newNode->prev=NULL;
if(*head!=NULL)
(*head)->prev=newNode;
*head=newNode;
}
else
{
while((p->next!=NULL) && k<pos-1)
{
p=p->next;
k++;
}
if((p->next)==NULL)
{
p->next=newNode;
newNode->next=NULL;
newNode->prev=p;
}
else
{
newNode->next=p->next;
newNode->prev=p;
p->next->prev=newNode;
p->next=newNode;
}
}
}
void del(DLLNode **head,int pos)
{
if(*head==NULL)
{
cout<<"List empty\n";
return;
}
DLLNode *temp=*head;
int k=1;
if(pos==1)
{
*head=(*head)->next;
if(*head!=NULL)
(*head)->prev=NULL;
delete temp;
}
else
{
while((temp->next!=NULL) && k<pos-1)
{
temp=temp->next;
k++;
}
if((temp->next)==NULL)
{
cout<<"Position exceeds list length\n";
return;
}
else
{
temp=temp->next;
temp->prev->next=temp->next;
if(temp->next!=NULL)
temp->next->prev=temp->prev;
delete temp;
}
}
}
void traversal(DLLNode **head)
{
if(*head==NULL)
{
cout<<"List empty\n";
return;
}
struct DLLNode *temp=new DLLNode;
temp=*head;
while(temp!=NULL)
{
cout<<temp->data<<" ";
temp=temp->next;
}
cout<<endl;
delete temp;
}
void deleteList(DLLNode ** head)
{
if(*head==NULL)
return;
DLLNode *p=*head;
while(p->next!=NULL)
{
DLLNode *temp=p->next;
p->next=temp->next;
delete temp;
}
delete p;
}
int main()
{
int pos,ch,val;
struct DLLNode *head=NULL;
do
{
cout<<"1. Insertion\n2. Deletion\n3. Traversal\n4. Exit\n";
cin>>ch;
switch (ch)
{
case 1: cout<<"Enter value and postion\n";
cin>>val>>pos;
insert(&head,val,pos);
break;
case 2: cout<<"Enter position\n";
cin>>pos;
del(&head,pos);
break;
case 3: traversal(&head);
break;
}
}while(ch!=4);
deleteList(&head);
return 0;
}