-
Notifications
You must be signed in to change notification settings - Fork 0
/
code.cpp
151 lines (136 loc) · 2.81 KB
/
code.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
147
148
149
150
151
#include<bits/stdc++.h>
#include <numeric>
#define pb push_back
#define pob pop_back()
#define mp make_pair
#define all(v) v.begin(),v.end()
#define IOS ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define fin(i,n1,n2);for(ll i=n1;i<n2;i++)
#define fde(i,n1,n2);for(ll i=n1;i>n2;i--)
#define M 1000000007
using ll=long long;
using ld=long double;
using namespace std;
//Arpcoder
bool comp(pair <ll,ll> &a,pair <ll,ll> &b)
{
if(a.first!=b.first)
return a.first>b.first;
else return a.second<b.second;
}
class Node
{
public:
ll data;
Node *next;
Node *prev;
Node(ll Data)
{
data=Data;
next=NULL;
prev=NULL;
}
};
void print(Node *&head)//passing by reference is not necessary as we r not making any changes
{
Node *temp=head;
while(temp!=NULL)
{
cout<<temp->data<<" ";
temp=temp->next;
}
cout<<"\n";
}
void InsertAtHead(Node *&head,ll d)
{
if(head==NULL)
{
Node *NodeToInsert=new Node(d);
head=NodeToInsert;
return;
}
Node *NodeToInsert=new Node(d);
NodeToInsert->next=head;
head->prev=NodeToInsert;
head=NodeToInsert;
}
void InsertAtTail(Node *&tail,ll d)
{
if(tail==NULL)
{
Node *NodeToInsert=new Node(d);
tail=NodeToInsert;
return;
}
Node *NodeToInsert=new Node(d);
tail->next=NodeToInsert;
NodeToInsert->prev=tail;
tail=NodeToInsert;
}
void InsertAtPosition(Node *&head,Node *&tail,ll d,ll pos)
{
if(pos==1)
{
InsertAtHead(head,d);
return;
}
Node *temp=head;
ll cnt=1;
while(cnt<pos-1)
{
temp=temp->next;
cnt++;
}
if(temp->next==NULL)
{
InsertAtTail(tail,d);
return;
}
Node *NodeToInsert=new Node(d);
NodeToInsert->next=temp->next;
NodeToInsert->prev=temp;
temp->next=NodeToInsert;
NodeToInsert->next->prev=NodeToInsert;
}
void deleteNode(Node *&head,ll pos)
{
if(pos==1)
{
Node *temp=head;
head=head->next;
head->prev=NULL;
free(temp);
return;
}
Node *p=head;
Node *q=head->next;
ll cnt=1;
while(cnt<pos-1)
{
q=q->next;
p=p->next;
cnt++;
}
p->next=q->next;
if(q->next!=NULL) //this statement throws error for tail elements ,thats why tail elements are not included via this condition;
q->next->prev=p;//for tail elements NULL->prev is not defined;
free(q);
}
int main()
{
Node *node1=new Node(2);
Node *head=node1;
Node *tail=node1;
InsertAtTail(tail,3);
print(head);
InsertAtHead(head,1);
print(head);
InsertAtPosition(head,tail,4,2);
print(head);
//cout<<tail->data;
deleteNode(head,2);
print(head);
deleteNode(head,3);
print(head);
//deleteNode(head,)
}