【linked list】Leetcode 876: Middle of the Linked List

https://leetcode.com/problems/middle-of-the-linked-list/

思路(快慢指针):
新建两个指针,循环的过程中,慢指针 slow 每次后移1位,快指针 fast 每次后移2位。

关于循环中止条件需要注意链表数量分别为奇数和偶数的情况不一样,分别是 fast == null, fast.next == null。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode middleNode(ListNode head) {
        ListNode p = head, q = head;
        
        while(q != null && q.next != null) {
            p = p.next;
            q = q.next.next;
        }
        return p;
    }
}

参考:https://youtu.be/Uk-PkL5WMMY

你可能感兴趣的:(【linked list】Leetcode 876: Middle of the Linked List)