Skip to content

Commit 2816669

Browse files
authored
Deleting node
Deleting the node in a singly linked list in c++
1 parent 4fdf861 commit 2816669

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

Deleting a node.cpp

+66
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
#include<bits/stdc++.h>
2+
3+
using namespace std;
4+
5+
class Node
6+
{
7+
public:
8+
int data;
9+
Node* next;
10+
};
11+
void push(Node** head_ref,int new_data)
12+
{
13+
14+
Node* new_node=new Node();
15+
16+
new_node->data=new_data;
17+
new_node->next=(*head_ref);
18+
(*head_ref)=new_node;
19+
}
20+
void deleteNode(Node** head_ref,int key)
21+
{
22+
Node* temp=(*head_ref),*prev;
23+
24+
if (temp != NULL && temp->data == key)
25+
{
26+
*head_ref = temp->next; // Changed head
27+
free(temp); // free old head
28+
return;
29+
}
30+
31+
while (temp != NULL && temp->data != key)
32+
{
33+
prev = temp;
34+
temp = temp->next;
35+
}
36+
if (temp == NULL) return;
37+
38+
prev->next = temp->next;
39+
40+
free(temp);
41+
}
42+
43+
void printList(Node *node)
44+
{
45+
while (node != NULL)
46+
{
47+
cout<< node->data;
48+
node = node->next;
49+
}
50+
}
51+
int main()
52+
{
53+
54+
Node* head = NULL;
55+
56+
push(&head, 7);
57+
push(&head, 1);
58+
push(&head, 3);
59+
push(&head, 2);
60+
61+
puts("Created Linked List: ");
62+
printList(head);
63+
deleteNode(&head, 1);
64+
puts("\nLinked List after Deletion of 1: ");
65+
printList(head);
66+
}

0 commit comments

Comments
 (0)