Skip to content

Commit 1c7448f

Browse files
committed
delete_at_begin.cpp file added
1 parent 6067df4 commit 1c7448f

File tree

1 file changed

+107
-0
lines changed

1 file changed

+107
-0
lines changed
Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
/*
2+
3+
This is a Doubly Linked List program which deletes a node at the beginning to the Linked List.
4+
Since, it is a Doubly Linked List, both the forward and backward traversal is also possible.
5+
6+
*/
7+
8+
#include <iostream>
9+
10+
using namespace std;
11+
12+
/*
13+
14+
Node definition:
15+
1. Pointer to previous node.
16+
2. Integer Data
17+
3. Pointer to next node.
18+
19+
*/
20+
21+
class dll_node {
22+
public:
23+
dll_node* prev;
24+
int data;
25+
dll_node* next;
26+
};
27+
28+
void createDLL(dll_node* &head) {
29+
30+
int choice;
31+
32+
dll_node* temp = head;
33+
34+
do {
35+
36+
int data;
37+
38+
cout << "Enter Data : ";
39+
cin >> data;
40+
41+
dll_node* newNode = new dll_node();
42+
newNode->data = data;
43+
newNode->prev = NULL;
44+
newNode->next = NULL;
45+
46+
if(head == NULL) {
47+
head = newNode;
48+
temp = head;
49+
} else {
50+
temp->next = newNode;
51+
newNode->prev = temp;
52+
temp = newNode;
53+
}
54+
55+
cout << "Do you want to continue? (1/0) : ";
56+
cin >> choice;
57+
58+
} while(choice == 1);
59+
60+
61+
}
62+
63+
void delete_at_begin(dll_node* &head) {
64+
65+
if(head == NULL)
66+
return;
67+
68+
if(head->next == NULL) {
69+
dll_node* temp = head;
70+
head = head->next;
71+
delete temp;
72+
return;
73+
}
74+
75+
dll_node* temp = head;
76+
head = head->next;
77+
head->prev = NULL;
78+
delete temp;
79+
return;
80+
81+
}
82+
83+
void display(dll_node* head) {
84+
cout << "The elements are : ";
85+
while(head != NULL) {
86+
cout << head->data << " ";
87+
head = head->next;
88+
}
89+
cout << endl;
90+
}
91+
92+
int main() {
93+
94+
dll_node* head = NULL;
95+
96+
createDLL(head);
97+
98+
cout << "Before Deletion : " << endl;
99+
display(head);
100+
101+
delete_at_begin(head);
102+
103+
cout << "After Deletion : " << endl;
104+
display(head);
105+
106+
return 0;
107+
}

0 commit comments

Comments
 (0)