Interview 150
Middle of the Linked List
- Problem
- LC 876
- File
- interview150_LC876MiddleOfTheLinkedList.java
- Path
- pkg5leetcode/interview150/interview150_LC876MiddleOfTheLinkedList.java
- Package
- pkg5leetcode.interview150
- Command
- java pkg5leetcode/interview150/interview150_LC876MiddleOfTheLinkedList.java
- Approach
- Slow/fast pointers; slow at middle when fast reaches end.
- Complexity
- Time O(n), Space O(1)
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg5leetcode.interview150;2 3/*4 * Middle of the Linked List | LC 8765 * APPROACH: Slow/fast pointers; slow at middle when fast reaches end.6 * COMPLEXITY: Time O(n), Space O(1)7 */8public class interview150_LC876MiddleOfTheLinkedList {9 /** Same shape as pkg5leetcode/common/ListNode.java (nested for single-file runs). */10 11 static class ListNode {12 int val;13 ListNode next;14 ListNode(int val) { this.val = val; }15 }16 17 static ListNode middleNode(ListNode head) {18 ListNode slow = head, fast = head;19 while (fast != null && fast.next != null) {20 slow = slow.next;21 fast = fast.next.next;22 }23 return slow;24 }25 26 static ListNode of(int... vals) {27 ListNode dummy = new ListNode(0), cur = dummy;28 for (int v : vals) { cur.next = new ListNode(v); cur = cur.next; }29 return dummy.next;30 }31 32 public static void main(String[] args) {33 check(middleNode(of(1, 2, 3, 4, 5)).val == 3, "case1");34 check(middleNode(of(1, 2, 3, 4, 5, 6)).val == 4, "case2");35 System.out.println("all tests passed");36 }37 38 static void check(boolean cond, String name) {39 if (!cond) throw new AssertionError("FAILED: " + name);40 System.out.println(" PASS " + name);41 }42}