Skip to content

Commit

Permalink
Add Return the k-th Node from the End Problem (#32)
Browse files Browse the repository at this point in the history
  • Loading branch information
xtenzQ authored Jul 21, 2024
1 parent 00632d4 commit 120b28c
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,26 @@ public static boolean hasCycle(ListNode head) {
}
return false;
}

/**
* Return the {@code k}-th node from the end of the linked list
*
* @param head of linked list
* @param k element position from the end
* @return node value of {@code k}-th node from the end
* @implNote This method runs in {@code O(n)} time complexity and {@code O(1)} space complexity
*/
public static int nodeFromEnd(ListNode head, int k) {
ListNode slow = head;
ListNode fast = head;
for (int i = 0; i < k; i++) {
fast = fast.next;
}

while (fast != null) {
slow = slow.next;
fast = fast.next;
}
return slow.val;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import static com.xtenzq.linkedlist.FastPointers.getMiddle;
import static com.xtenzq.linkedlist.FastPointers.hasCycle;
import static com.xtenzq.linkedlist.FastPointers.nodeFromEnd;
import static com.xtenzq.linkedlist.utils.ListNode.buildLinkedList;
import static com.xtenzq.linkedlist.utils.ListNode.buildLinkedListWithCycle;
import static org.junit.jupiter.api.Assertions.assertEquals;
Expand Down Expand Up @@ -38,4 +39,14 @@ void hasCycle_case2() {
void hasCycle_case3() {
assertFalse(hasCycle(buildLinkedListWithCycle(new int[]{1}, -1)));
}

@Test
void nodeFromEnd_case1() {
assertEquals(4, nodeFromEnd(buildLinkedList(1, 2, 3, 4, 5), 2));
}

@Test
void nodeFromEnd_case2() {
assertEquals(1, nodeFromEnd(buildLinkedList(1), 1));
}
}

0 comments on commit 120b28c

Please sign in to comment.