-
Notifications
You must be signed in to change notification settings - Fork 83
/
nth_node_deletion.cpp
105 lines (78 loc) · 1.34 KB
/
nth_node_deletion.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
#include<bits/stdc++.h>
using namespace std;
class LinkedList
{
public:
class Node
{
public:
int data;
Node* next;
Node(int d)
{
data = d;
next = NULL;
}
};
Node* head;
Node* deleteNode(int key)
{
Node *temp;
Node *first = head;
Node *second = head;
for (int i = 0; i < key; i++)
{
if (second->next == NULL)
{
if (i == key - 1){
temp = head;
head = head->next;
free (temp);
}
return head;
}
second = second->next;
}
while (second->next != NULL)
{
first = first->next;
second = second->next;
}
temp = first->next;
first->next = first->next->next;
free (temp);
return head;
}
Node* push(int new_data)
{
Node* new_node = new Node(new_data);
new_node->next = head;
head = new_node;
return head;
}
void printList()
{
Node* tnode = head;
while (tnode != NULL)
{
cout << (tnode->data) << ( " ");
tnode = tnode->next;
}
}
};
int main()
{
LinkedList* llist = new LinkedList();
llist->head = llist->push(10);
llist->head = llist->push(5);
llist->head = llist->push(23);
llist->head = llist->push(45);
cout << ("Linked list:\n");
llist->printList();
int N;
cout << ("\n\nEnter the Nth node to be deleted: ");
cin >> N;
llist->head = llist->deleteNode(N);
cout << ("\nLinked List after Deletion:\n");
llist->printList();
}