-
Notifications
You must be signed in to change notification settings - Fork 0
/
075_DeleteKthNodeFromEnd.cpp
59 lines (48 loc) · 1.17 KB
/
075_DeleteKthNodeFromEnd.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
#include<bits/stdc++.h>
using namespace std;
/****************************************************************
Following is the class structure of the LinkedListNode class:
*****************************************************************/
template <typename T>
class LinkedListNode
{
public:
T data;
LinkedListNode<T> *next;
LinkedListNode(T data)
{
this->data = data;
this->next = NULL;
}
};
LinkedListNode<int>* reverseLL(LinkedListNode<int>* head){
LinkedListNode<int>* curr=head;
LinkedListNode<int>* prev=NULL;
while(head){
curr=head;
head=head->next;
curr->next=prev;
prev=curr;
}
return head=curr;
}
LinkedListNode<int>* removeKthNode(LinkedListNode<int> *head, int K)
{
// Write your code here.
if(!head || !K) return head;
head=reverseLL(head);
if(K==1){
head=head->next;
}else{
LinkedListNode<int>* prev=NULL;
LinkedListNode<int>* curr=head;
while(--K && curr){
prev=curr;
curr=curr->next;
}
prev->next=curr->next;
delete curr;
}
head=reverseLL(head);
return head;
}