876. Middle of the Linked List - LeetCode

Question

876. Middle of the Linked List java

Solution

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

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

Java實現:leetcode

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;
}
相關文章
相關標籤/搜索