-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDelete_kth_node_from_end.cpp
57 lines (54 loc) · 1000 Bytes
/
Delete_kth_node_from_end.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
/*
Following is the class structure of the Node class:
class Node
{
public:
int data;
Node *next;
Node()
{
this->data = 0;
next = NULL;
}
Node(int data)
{
this->data = data;
this->next = NULL;
}
Node(int data, Node* next)
{
this->data = data;
this->next = next;
}
};
*/
Node *removeKthNode(Node *head, int K)
{
// Write your code here.
Node *fast = head;
Node *slow = head;
if (head == NULL || K == 0)
return head;
for (int i = 1; i <= K; i++)
{
if (fast == NULL)
return head;
fast = fast->next;
}
if (fast == NULL)
{
Node *todelete = head;
head = head->next;
delete todelete;
return head;
}
while (fast->next != NULL)
{
fast = fast->next;
slow = slow->next;
}
Node *todelete = slow->next;
slow->next = slow->next->next;
delete todelete;
return head;
}