Skip to content

Commit bb5bc5b

Browse files
committed
Remove Kth Last Node
1 parent 544554a commit bb5bc5b

File tree

2 files changed

+68
-1
lines changed

2 files changed

+68
-1
lines changed

Java/src/CodeRunner/LinkedListsRunner.java

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,9 @@ public static void main(String[] args) {
1616

1717
// System.out.println(testLinkedListReversalRecursive());
1818

19-
System.out.println(testPalindromicLinkedList());
19+
// System.out.println(testPalindromicLinkedList());
20+
21+
System.out.println(testRemoveKthLastNode());
2022

2123
// System.out.println(testLRUCache());
2224

@@ -156,6 +158,25 @@ private static boolean testPalindromicLinkedList() {
156158
return true;
157159
}
158160

161+
private static boolean testRemoveKthLastNode() {
162+
int[] valsA = {1, 2, 3, 4, 5};
163+
int k = 2;
164+
ListNode headA = makeList(valsA);
165+
System.out.println("Printing list A before");
166+
System.out.println(listNodeToString(headA));
167+
168+
headA = RemoveKthLastNode.Solution(headA, k);
169+
170+
if (!verifyLinkedList(headA, new int[] {1, 2, 4, 5})) {
171+
return false;
172+
}
173+
174+
System.out.println("Printing list A after");
175+
System.out.println(listNodeToString(headA));
176+
177+
return true;
178+
}
179+
159180
private static boolean testLRUCache() {
160181
LRUCache lru1 = new LRUCache(3);
161182

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package LinkedLists;
2+
3+
import DS.ListNode;
4+
5+
/*
6+
// Definition of ListNode:
7+
public class ListNode {
8+
public int val;
9+
public ListNode next;
10+
public ListNode(int val) { this.val = val; }
11+
public ListNode(int val, ListNode next) {
12+
this(val);
13+
this.next = next;
14+
}
15+
}
16+
*/
17+
18+
19+
public class RemoveKthLastNode {
20+
public static ListNode Solution(ListNode head, int k) {
21+
// A dummy node to ensure there's a node before 'head' in case we
22+
// need to remove the head node.
23+
ListNode dummy = new ListNode(-1);
24+
dummy.next = head;
25+
ListNode trailer = dummy;
26+
ListNode leader = head;
27+
// Advance 'leader' k steps ahead.
28+
for (int i = 0; i < k; i++) {
29+
leader = leader.next;
30+
// If k is larger than the length of the linked list, no node
31+
// needs to be removed.
32+
if (leader == null) {
33+
return head;
34+
}
35+
}
36+
// Move 'leader' to the end of the linked list, keeping 'trailer'
37+
// k nodes behind.
38+
while (leader.next != null) {
39+
leader = leader.next;
40+
trailer = trailer.next;
41+
}
42+
// Remove the kth node from the end.
43+
trailer.next = trailer.next.next;
44+
return dummy.next;
45+
}
46+
}

0 commit comments

Comments
 (0)