-
Notifications
You must be signed in to change notification settings - Fork 33
/
deletingInLinkedList.cpp
105 lines (86 loc) · 1.75 KB
/
deletingInLinkedList.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
// C++ program to delete a node in
// singly linked list recursively
#include <bits/stdc++.h>
using namespace std;
struct node {
int info;
node* link = NULL;
node() {}
node(int a)
: info(a)
{
}
};
// Deletes the node containing 'info'
// part as val and alter the head of
// the linked list (recursive method)
void deleteNode(node*& head, int val)
{
// Check if list is empty or we
// reach at the end of the
// list.
if (head == NULL) {
cout << "Element not present in the list\n";
return;
}
// If current node is the
// node to be deleted
if (head->info == val) {
node* t = head;
// If it's start of the node head
// node points to second node
head = head->link;
// Else changes previous node's
// link to current node's link
delete (t);
return;
}
deleteNode(head->link, val);
}
// Utility function to add a
// node in the linked list
// Here we are passing head by
// reference thus no need to
// return it to the main function
void push(node*& head, int data)
{
node* newNode = new node(data);
newNode->link = head;
head = newNode;
}
// Utility function to print
// the linked list (recursive
// method)
void print(node* head)
{
// cout<<endl gets implicitly
// typecasted to bool value
// 'true'
if (head == NULL and cout << endl)
return;
cout << head->info << ' ';
print(head->link);
}
int main()
{
// Starting with an empty linked list
node* head = NULL;
// Adds new element at the
// beginning of the list
push(head, 10);
push(head, 12);
push(head, 14);
push(head, 15);
// original list
print(head);
// Call to delete function
deleteNode(head, 20);
// 20 is not present thus no change
// in the list
print(head);
deleteNode(head, 10);
print(head);
deleteNode(head, 14);
print(head);
return 0;
}