1. 程式人生 > >876. Middle of the Linked List - LeetCode

876. Middle of the Linked List - LeetCode

ble 題目 兩個 etc ems eno The lin clas

Question

876.?Middle of the Linked List

技術分享圖片

Solution

題目大意:求鏈表的中間節點

思路:構造兩個節點,遍歷鏈接,一個每次走一步,另一個每次走兩步,一個遍歷完鏈表,另一個恰好在中間

Java實現:

public ListNode middleNode(ListNode head) {
    ListNode slow = head;
    ListNode fast = head;
    while (fast != null) {
        fast = fast.next;
        if(fast != null) {
            fast = fast.next;
            slow = slow.next;
        }
    }
    return slow;
}

876. Middle of the Linked List - LeetCode