-
Notifications
You must be signed in to change notification settings - Fork 0
/
Doubly_Linked_List.cpp
144 lines (137 loc) · 2.08 KB
/
Doubly_Linked_List.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
#include<iostream>
using namespace std;
class node{
private:
int data;
node *next;
node *prev;
public:
node(int d)
{
data=d;
next=NULL;
prev=NULL;
}
friend class Linked_List;
};
class Linked_List
{
private:
node *head;
public:
Linked_List()
{
head=NULL;
}
void insertatbeg(int d)
{
node *n=new node(d);
n->next=head;
n->prev=NULL;
head=n;
}
void insertatend(int d)
{
node *t=head;
node *n=new node(d);
while(t->next!=NULL)
{
t=t->next;
}
t->next=n;
n->prev=t;
}
void insertatK(int d,int k)
{
node *n=new node(d);
node *t=head;
node *temp=NULL;
int cnt=1;
while(head==NULL || k==1)
{
insertatbeg(d);
return;
}
while(t->next!=NULL && cnt<k)
{
temp=t;
t=t->next;
cnt++;
}
n->prev=temp;
n->next=temp->next;
temp->next=n;
t->prev=n;
}
void print()
{
node *t=head;
while(t!=NULL)
{
cout<<t->data<<" ->";
t=t->next;
}
cout<<endl;
}
void delatbeg()
{
if(head==NULL)
{
cout<<"no nodes left"<<endl;
return;
}
node*t=head;
head=t->next;
head->prev=NULL;
t->next=NULL;
delete t;
}
void delatend()
{
node *t=head;
while(t->next!=NULL)
{
t=t->next;
}
t->prev->next=NULL;
delete t;
}
void delatK(int k)
{
int cnt=1;
node *t=head;
node*temp=NULL;
node *temp2=NULL;
while(t->next!=NULL && cnt<k-1)
{
t=t->next;
cnt++;
}
temp=t->next;
t->next=temp->next;
temp->next->prev=t;
temp->next=NULL;
delete temp;
}
};
int main()
{
Linked_List ll;
int d,c;
char choice;
ll.insertatbeg(1);
ll.insertatbeg(2);
ll.print();
ll.insertatend(3);
ll.print();
ll.insertatK(4,3);
ll.print();
//ll.delatbeg();
//ll.print();
//ll.delatend();
//ll.print();
ll.delatK(2);
ll.print();
// ll.delatK(3);
//ll.print();
}