Monday, June 20, 2022

876. Middle of the Linked List

 一刷 06/2022

Version #1 Two Pointers

Time O(N)

Space O(1)

Runtime: 0 ms, faster than 100.00% of Java online submissions for Middle of the Linked List.
Memory Usage: 41.4 MB, less than 60.64% of Java online submissions for Middle of the Linked List.

/**

 * Definition for singly-linked list.

 * public class ListNode {

 *     int val;

 *     ListNode next;

 *     ListNode() {}

 *     ListNode(int val) { this.val = val; }

 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }

 * }

 */

class Solution {

    //     s

    //          f

    // 1 2 3 4

    //   s

    //     f

    // 1 2 3

    public ListNode middleNode(ListNode head) {

        ListNode slow = head, fast = head;

        while (fast != null && fast.next != null) {

            slow = slow.next;

            fast = fast.next.next;

        }

        return slow;

    }

}

No comments:

Post a Comment