-
Notifications
You must be signed in to change notification settings - Fork 0
/
Delete_without_head_pointer.cpp
127 lines (107 loc) · 1.99 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
//{ Driver Code Starts
#include<bits/stdc++.h>
using namespace std;
/* Link list node */
struct Node {
int data;
struct Node *next;
Node(int x) {
data = x;
next = NULL;
}
}*head;
Node *findNode(Node* head, int search_for)
{
Node* current = head;
while (current != NULL)
{
if (current->data == search_for)
break;
current = current->next;
}
return current;
}
void insert()
{
int n,i,value;
Node *temp;
scanf("%d",&n);
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 to print linked list */
void printList(Node *node)
{
while (node != NULL)
{
printf("%d ", node->data);
node = node->next;
}
cout << endl;
}
// } Driver Code Ends
/*
struct Node {
int data;
struct Node *next;
Node(int x) {
data = x;
next = NULL;
}
}*head;
*/
class Solution
{
public:
//Function to delete a node without any reference to head pointer.
void deleteNode(Node *del)
{
Node * temp = head;
if(head == del) {
head = head->next;
return;
}
while(temp != NULL && temp->next != del) {
temp = temp->next;
}
if(temp != NULL) {
temp->next = temp->next->next;
}
}
};
//{ Driver Code Starts.
/* Drier program to test above function*/
int main(void)
{
/* Start with the empty list */
int t,k,n,value;
scanf("%d",&t);
while(t--)
{
insert();
scanf("%d",&k);
Node *del = findNode(head, k);
Solution ob;
if (del != NULL && del->next != NULL)
{
ob.deleteNode(del);
}
printList(head);
}
return(0);
}
// } Driver Code Ends