算法(常用)——快速找到链表的中间节点

思路:利用快慢指针思想,快指针每次走两步,慢指针走一步。当快指针走到底的时候,满指针指向的就是链表的中间节点。需要注意的是,当链表长度为偶数位的时候,则慢指针指向的是中间偏右的节点,奇数的时候,指向的是中间节点。

        if(head == null || head.next == null) return true;

        ListNode fast = head, slow = head;

        while(fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }

		// 如果 fast == null,则链表长度为偶数,反之则为奇数。
posted @ 2020-11-03 16:39  lippon  阅读(401)  评论(0编辑  收藏  举报