forked from Mugdha-Hazra/PrepBytes-questions
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Delete kth Node From End of List.cpp
123 lines (105 loc) · 2.2 KB
/
Delete kth Node From End of 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
// C++ implementation of the approach
#include<bits/stdc++.h>
using namespace std;
class LinkedList
{
public:
// Linked list Node
class Node
{
public:
int data;
Node* next;
Node(int d)
{
data = d;
next = NULL;
}
};
// Head of list
Node* head;
// Function to delete the nth node from
// the end of the given linked list
Node* deleteNode(int key)
{
// First pointer will point to
// the head of the linked list
Node *first = head;
// Second pointer will point to the
// Nth node from the beginning
Node *second = head;
for (int i = 0; i < key; i++)
{
// If count of nodes in the given
// linked list is <= N
if (second->next == NULL)
{
// If count = N i.e.
// delete the head node
if (i == key - 1)
head = head->next;
return head;
}
second = second->next;
}
// Increment both the pointers by one until
// second pointer reaches the end
while (second->next != NULL)
{
first = first->next;
second = second->next;
}
// First must be pointing to the
// Nth node from the end by now
// So, delete the node first is pointing to
first->next = first->next->next;
return head;
}
// Function to insert a new Node
// at front of the list
Node* push(int new_data)
{
Node* new_node = new Node(new_data);
new_node->next = head;
head = new_node;
return head;
}
// Function to print the linked list
void printList()
{
Node* tnode = head;
while (tnode != NULL)
{
cout << (tnode->data) << ( " ");
tnode = tnode->next;
}
}
};
// Driver code
int main()
{ int t;
cin>>t;
while(t--)
{ int i,n,k,a[1000000];
cin>>n>>k;
LinkedList* llist = new LinkedList();
for( i=0;i<n;i++)
{ cin>>a[i];
// llist->head = llist->push(a[i]);
}
for(i=n-1;i>=0;i--)
{
llist->head = llist->push(a[i]);
}
//llist->head = llist->push(7);
//llist->head = llist->push(1);
//llist->head = llist->push(3);
//llist->head = llist->push(2);
//cout << ("Created Linked list is:\n");
//llist->printList();
//int N = 1;
llist->head = llist->deleteNode(k);
//cout << ("\nLinked List after Deletion is:\n");
llist->printList();
} return 0;
}