-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDelete a Node in Single Linked List.cpp
164 lines (138 loc) · 2.74 KB
/
Delete a Node in Single Linked List.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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
//{ Driver Code Starts
// C program to find n'th Node in linked list
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
/* Link list Node */
struct Node
{
int data;
struct Node *next;
Node(int x)
{
data = x;
next = NULL;
}
};
void append(struct Node **head_ref, struct Node **tail_ref,
int new_data)
{
struct Node *new_node = new Node(new_data);
if (*head_ref == NULL)
*head_ref = new_node;
else
(*tail_ref)->next = new_node;
*tail_ref = new_node;
}
/* Function to get the middle of the linked list*/
struct Node *deleteNode(struct Node *head, int);
void printList(Node *head)
{
while (head != NULL)
{
cout << head->data << " ";
head = head->next;
}
cout << "\n";
}
/* Driver program to test above function*/
int main()
{
int T, i, n, l;
cin >> T;
while (T--)
{
struct Node *head = NULL, *tail = NULL;
cin >> n;
for (i = 1; i <= n; i++)
{
cin >> l;
append(&head, &tail, l);
}
int kk;
cin >> kk;
head = deleteNode(head, kk);
printList(head);
}
return 0;
}
// } Driver Code Ends
/* Link list Node
struct Node
{
int data;
struct Node* next;
Node(int x){
data = x;
next = NULL;
}
};
*/
/*You are required to complete below method*/
/*
Delete a Node in Single Linked List
Input:
1
5
5 3 4 1 2
4
Output:
5 3 4 2
Explanation Recursive:
deleteNode(1639,2)
deleteNode(639,1)
deleteNode(412,2)
deleteNode(12,1)
return 2
return 42
return 342
return 5342
*/
// Recursive Solution:
// Node *deleteNode(Node *head, int x)
// {
// if (!head)
// {
// return NULL;
// }
// if (x == 1)
// {
// return head->next;
// }
// head->next = deleteNode(head->next, x - 1);
// return head;
// }
// Iterative Solution:
struct Node *deleteNode(struct Node *head, int k)
{
if (head == NULL)
{
return NULL;
}
// If k is 1, delete the first node and return the new head
if (k == 1)
{
Node *temp = head;
head = head->next;
free(temp);
return head;
}
else
{
// Initialize iterators
Node *temp = head;
Node *back;
// Move temp and back pointers until reaching the kth node or the end of the list
while (temp != NULL && k > 1)
{
back = temp;
temp = temp->next;
k--;
}
// Update the previous node's next pointer to skip the kth node, i.e. k = 1 is reached
back->next = temp->next;
free(temp);
return head;
}
}