-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdoubly_linkedlist_basics.cpp
120 lines (120 loc) · 1.99 KB
/
doubly_linkedlist_basics.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
#include <bits/stdc++.h>
using namespace std;
struct node
{
node* next;
node* prev;
int data;
};
void print_list(node** head)
{
node *temp=*head;
while(temp!=NULL)
{
cout<<temp->data<<" ";
temp=temp->next;
}
cout<<"\n";
}
void insert_element(node** new_node,int index,node** head,node** tail,int n)
{
if(index==1)
{
(*new_node)->next=*head;
(*head)->prev=*new_node;
*head=*new_node;
}
else if(index==n)
{
(*tail)->next=*new_node;
(*new_node)->prev=*tail;
*tail=*new_node;
}
else
{
node* current=*head;
while(index!=1)
{
index--;
current=current->next;
}
(*new_node)->next=current->next;
current->next=*new_node;
(*new_node)->prev=current;
}
}
void delete_element(int index,node** head,node** tail,int n)
{
if(index==1)
{
node* temp=*head;
*head=(*head)->next;
(*head)->prev=NULL;
delete temp;
}
else if(index==n)
{
node* temp=*tail;
node* current=*head;
while(current->next->next!=NULL)
{
current=current->next;
}
*tail=current;
(*tail)->next=NULL;
delete temp;
}
else
{
node* current=*head;
node* temp=NULL;
while(index!=1)
{
index--;
temp=current;
current=current->next;
}
temp->next=current->next;
current->prev=NULL;
delete current;
}
}
int main()
{
int n;
cin>>n;
node* head=NULL;
node* tail=NULL;
for(int i=0;i<n;i++)
{
node* temp=new node();
int j;
cin>>j;
temp->data=j;
temp->next=NULL;
temp->prev=NULL;
if(i==0)
{
head=temp;
tail=temp;
}
else
{
tail->next=temp;
temp->prev=tail;
tail=temp;
}
}
print_list(&head);
node* temp=new node();
int j,index;
cin>>j>>index;
temp->data=j;
temp->next=NULL;
temp->prev=NULL;
insert_element(&temp,index,&head,&tail,n);
n++;
delete_element(3,&head,&tail,n);
print_list(&head);
return 0;
}