forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Delete_without_head_pointer.cpp
136 lines (123 loc) · 2.62 KB
/
Delete_without_head_pointer.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
/*
Description :
Given a pointer/ reference to the node which is
to be deleted from the linked list of N number nodes.
The task is to delete the node. Pointer/ reference to head node is not given.
*/
#include <bitset/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node *next;
Node(int x)
{
data = x;
next = NULL;
}
} * head;
// function used to search the data which is given by user
Node *search_node(Node *head, int search_for_data)
{
Node *current = head;
while (current != NULL)
{
// if data found then break
if (current->data == search_for_data)
{
break;
}
current = current->next;
}
return current;
}
//function used for the inserting the data into the tree.
void insert_node()
{
// n= number of nodes in tree
int n, i, value;
Node *temp;
cout << "Enter the number of nodes : " << endl;
scanf("%d", &n);
cout << "Enter the data : " << endl;
for (i = 0; i < n; i++)
{
scanf("%d", &value);
if (i == 0)
{
head = new Node(value);
temp = head;
continue;
}
else
{
temp->next = new Node(value);
temp = temp->next;
temp->next = NULL;
}
}
}
// function used for the printing the data of the tree
void print_tree(Node *node)
{
while (node != NULL)
{
cout << node->data << " ";
node = node->next;
}
cout << endl;
}
// another class
class Solution
{
public:
// function used to delete the data given by user
// head pointer is not given
// reference given of the node to be deleted
void to_delete_node(Node *del)
{
if (del->next == NULL)
{
return;
}
Node *temp_1 = del->next;
del->data = temp_1->data;
del->next = del->next->next;
delete (temp_1);
}
};
int main()
{
// k = storing data to be deleted
int k;
insert_node();
cout << "Enter data to delete : " << endl;
scanf("%d", &k);
Node *del = search_node(head, k);
Solution obj;
//deleting the given data by user
if (del != NULL && del->next != NULL)
{
obj.to_delete_node(del);
}
cout << "Tree after deleting " << k << " : " << endl;
print_tree(head);
return 0;
}
/*
Time complexity : O(n)
Space complexity : O(n)
*/
/*
Test Case :
Input :
Enter the number of nodes :
4
Enter the data :
1 2 3 4
Enter data to delete :
3
Output :
Tree after deleting 3 :
1 2 4
*/