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;
}
相关文章
相关标签/搜索