-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDeleteKthnodeFromEnd
43 lines (34 loc) · 1.15 KB
/
DeleteKthnodeFromEnd
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
import java.util.* ;
import java.io.*;
/****************************************************************
Following is the structure of the Singly Linked List.
class LinkedListNode<T> {
T data;
LinkedListNode<T> next;
public LinkedListNode(T data) {
this.data = data;
}
}
****************************************************************/
public class Solution {
public static LinkedListNode<Integer> removeKthNode(LinkedListNode<Integer> head, int K) {
// Write your code here.
if(K == 0 || head == null)
return head;
LinkedListNode<Integer> start = new LinkedListNode<Integer>(1);
LinkedListNode<Integer> slow = start;
LinkedListNode<Integer> fast = start;
start.next = head;
for(int i = 0; i < K && fast != null; i++){
fast = fast.next;
}
if(fast == null)
return head;
while(fast.next != null){
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return start.next;
}
}