-
Notifications
You must be signed in to change notification settings - Fork 232
/
Deleting Node in Linked List
77 lines (69 loc) · 1.22 KB
/
Deleting Node in Linked List
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
#include <bits/stdc++.h>
using namespace std;
struct Node {
int number;
Node* next;
};
void Push(Node** head, int A)
{
Node* n = (Node*)malloc(sizeof(Node));
n->number = A;
n->next = *head;
*head = n;
}
void deleteN(Node** head, int position)
{
Node* temp;
Node* prev;
temp = *head;
prev = *head;
for (int i = 0; i < position; i++) {
if (i == 0 && position == 1) {
*head = (*head)->next;
free(temp);
}
else {
if (i == position - 1 && temp) {
prev->next = temp->next;
free(temp);
}
else {
prev = temp;
// Position was greater than
// number of nodes in the list
if (prev == NULL)
break;
temp = temp->next;
}
}
}
}
void printList(Node* head)
{
while (head) {
if (head->next == NULL)
cout << "[" << head->number << "] "
<< "[" << head << "]->"
<< "(nil)" << endl;
else
cout << "[" << head->number << "] "
<< "[" << head << "]->" << head->next
<< endl;
head = head->next;
}
cout << endl << endl;
}
// Driver code
int main()
{
Node* list = (Node*)malloc(sizeof(Node));
list->next = NULL;
Push(&list, 1);
Push(&list, 2);
Push(&list, 3);
printList(list);
// Delete any position from list
deleteN(&list, 1);
printList(list);
return 0;
}