Repository navigation
Expand file tree
/
Copy pathDeleteValueAtPositionInDoublyLinkedList.cpp
More file actions
96 lines (95 loc) · 2.37 KB
/
Copy pathDeleteValueAtPositionInDoublyLinkedList.cpp
File metadata and controls
96 lines (95 loc) · 2.37 KB
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
/*
* Delete Value at Position in Doubly Linked List
*
* This program deletes a node at a specified position from a doubly linked list.
* It handles deletion of head, tail, and middle nodes while properly updating
* the prev and next pointers to maintain list connectivity. The implementation
* uses 1-based indexing for position specification. Input consists of list size,
* followed by list elements, and finally the position to delete. Output displays
* the updated list after deletion.
*/
// You are using GCC
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
Node* prev;
};
class DoubleList {
public:
Node* head = nullptr;
Node* tail = nullptr;
int length = 0;
void pushToEnd(int val) {
Node* newNode = new Node();
newNode->data = val;
if (!head) {
newNode->next = nullptr;
newNode->prev = nullptr;
head = tail = newNode;
length++;
return;
}
tail->next = newNode;
newNode->prev = tail;
newNode->next = nullptr;
tail = newNode;
length++;
}
void deleteAtPos(int num) {
int pos = num;
int count = 1;
if (pos == 1) {
Node*temp = head->next;
temp->prev = nullptr;
delete head;
head = temp;
length--;
return;
}
if (pos == length) {
Node* temp = tail->prev;
delete tail;
temp->next = nullptr;
tail = temp;
length--;
return;
}
Node* temp = head;
while (temp) {
if (count == pos) {
Node* temp2 = temp->prev;
temp2->next = temp->next;
Node* temp3 = temp->next;
temp3->prev = temp->prev;
delete temp;
return;
}
temp = temp->next;
count++;
}
}
void printList() {
Node* temp = head;
while (temp) {
cout<<temp->data<<" ";
temp = temp->next;
}
cout<<endl;
}
};
int main() {
int size;
cin>>size;
DoubleList d;
int val;
for (int i = 0 ; i < size ; i ++) {
cin>>val;
d.pushToEnd(val);
}
int pos;
cin>>pos;
d.deleteAtPos(pos);
d.printList();
}