forked from Algo-Phantoms/Algo-Tree
-
Notifications
You must be signed in to change notification settings - Fork 0
/
delete_without_head.cpp
130 lines (117 loc) · 2.57 KB
/
delete_without_head.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
/*
This method is about deleting any node in the given linked list without the use of head pointer
in this menthod we are going to apporoach like this:
1. we will start off by storing the node next to given node in a pointer.
2. the next step would be copying the data of pointer in the given current node.
3. then storing the next node to pointer in link part of current node.
4. ans the last step of freeing up the used memory manually using free().
*/
#include<bits/stdc++.h>
#include<iostream>
using namespace std;
struct Node {
int info;
struct Node *next;
Node(int x) {
info = x;
next = NULL;
}
}*head;
void insert()
{
int n,k,data;
Node *temp;
scanf("%d",&n);
for(k=0; k<n; k++)
{
scanf("%d",&data);
if(k==0)
{
head=new Node(data);
temp=head;
continue;
}
else
{
temp->next= new Node(data);
temp=temp->next;
temp->next=NULL;
}
}
}
void printLL(Node *node)
{
while (node != NULL)
{
printf("%d ", node->info);
node = node->next;
}
cout << endl;
}
Node *find(Node* head, int search)
{
Node* curr = head;
while (curr != NULL)
{
if (curr->info == search)
break;
curr = curr->next;
}
return curr;
}
void deleteNodewohead(Node *node_ptr);
int main(void)
{ int tests,a,n,data;
scanf("%d",&tests);
while(tests--)
{
insert();
scanf("%d",&a);
Node *dele = find(head, a);
if (dele != NULL && dele->next != NULL)
{
deleteNodewohead(dele);
}
printLL(head);
}
return(0);
}
void deleteNodewohead(Node *node)
{
//It is assumed that the node asked to delete is not the last node but we can always try this :-
// if(node->next!=NULL)
// {
// *node=*node->next;
// return;
// }
// node=NULL;
if(!node->next){
return;
}
Node *delet= node->next;
node->info=delet->info;
node->next=delet->next;
free(delet);
}
/*
sample case 1:
Input:
N = 4
value[] = {10,20,4,30}
node = 20
Output: 10 4 30
Explanation: After deleting 20 from
the linked list, we have remaining
nodes as 10, 4 and 30.
Sample case 2:
Input:
N = 2
value[] = {1,2}
node = 1
Output: 2
Explanation: After deleting 1 from the
linked list, we have remaining nodes
as 2.
Time complexity--> O(1)
Auxilliary Space--> O(1)
*/