1
+ #include < iostream>
2
+ using namespace std ;
3
+
4
+ class Node {
5
+ public:
6
+ int data;
7
+ Node* prev;
8
+ Node* next;
9
+
10
+ Node (int d){
11
+ this ->data = d;
12
+ this ->next = NULL ;
13
+ this ->prev = NULL ;
14
+ }
15
+
16
+ ~Node () {
17
+ int val = this -> data;
18
+ if (next != NULL ) {
19
+ delete next;
20
+ next = NULL ;
21
+ }
22
+ cout << " memory free for node with data " << val << endl;
23
+ }
24
+ };
25
+
26
+ void print (Node* &head){
27
+ Node* temp = head;
28
+
29
+ while (temp != NULL ){
30
+ cout<< temp ->data << " " ;
31
+ temp = temp ->next ;
32
+ }
33
+ cout << endl;
34
+ }
35
+
36
+ void insertAtHead (Node* &tail, Node* &head, int d){
37
+ // empty list
38
+ if (head==NULL ){
39
+ Node* temp = new Node (d);
40
+ head = temp;
41
+ tail = temp;
42
+ }
43
+ else {
44
+ Node* temp = new Node (d);
45
+ temp ->next = head;
46
+ head ->prev = temp;
47
+ head = temp;
48
+ }
49
+ }
50
+
51
+ void insertAtTail (Node* &tail, Node* &head, int d){
52
+ // empty list
53
+ if (tail==NULL ){
54
+ Node* temp = new Node (d);
55
+ tail = temp;
56
+ head = temp;
57
+ }
58
+ else {
59
+ Node* temp = new Node (d);
60
+ tail ->next = temp;
61
+ temp ->prev = tail;
62
+ tail = temp;
63
+ }
64
+ }
65
+
66
+ void insertNode (Node* &tail, Node* &head, int pos, int d){
67
+ // insert start
68
+ if (pos==1 ){
69
+ insertAtHead (tail, head, d);
70
+ return ;
71
+ }
72
+
73
+ Node* temp = head;
74
+ int c = 1 ;
75
+ while (c < pos-1 ){
76
+ temp = temp ->next ;
77
+ c++;
78
+ }
79
+
80
+ // insert at end
81
+ if (temp -> next == NULL ){
82
+ insertAtTail (tail, head, d);
83
+ return ;
84
+ }
85
+
86
+ // creating a new node
87
+ Node* nodetoInsert = new Node (d);
88
+ nodetoInsert -> next = temp ->next ;
89
+ temp ->next ->prev = nodetoInsert;
90
+ temp ->next = nodetoInsert;
91
+ nodetoInsert ->prev = temp;
92
+ }
93
+
94
+ void deleteNode (int position, Node* & head) {
95
+
96
+ // deleting first or start node
97
+ if (position == 1 ) {
98
+ Node* temp = head;
99
+ temp -> next -> prev = NULL ;
100
+ head = temp ->next ;
101
+ temp -> next = NULL ;
102
+ delete temp;
103
+ }
104
+ else
105
+ {
106
+ // deleting any middle node or last node
107
+ Node* curr = head;
108
+ Node* prev = NULL ;
109
+
110
+ int cnt = 1 ;
111
+ while (cnt < position) {
112
+ prev = curr;
113
+ curr = curr -> next;
114
+ cnt++;
115
+ }
116
+
117
+ curr -> prev = NULL ;
118
+ prev -> next = curr -> next;
119
+ curr -> next = NULL ;
120
+
121
+ delete curr;
122
+
123
+ }
124
+ }
125
+
126
+ int main (){
127
+ // Node* node1 = new Node(10);
128
+ Node* head = NULL ;
129
+ Node* tail = NULL ;
130
+
131
+ insertNode (tail, head, 1 , 1 );
132
+ print (head);
133
+
134
+ insertAtHead (tail, head, 12 );
135
+ print (head);
136
+
137
+ insertAtTail (tail, head, 15 );
138
+ print (head);
139
+
140
+ insertNode (tail, head, 2 , 30 );
141
+ print (head);
142
+
143
+ insertNode (tail, head, 1 , 10 );
144
+ print (head);
145
+
146
+ return 0 ;
147
+ }
0 commit comments