[LeetCode题解]876. 链表的中间结点 | 快慢指针

解题思路

使用快慢指针。这里要注意的是,while 的条件会影响当中间节点有两个时,slow 指向的是第一个,还是第二个节点。

// 返回的是第一个
while(fast.next != null && fast.next.next != null)


// 返回的是第二个
while(fast != null && fast.next != null)

代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode MiddleNode(ListNode head) {
        // 快慢指针
        ListNode fast = head, slow = head;
        while(fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }

        return slow;
    }
}

复杂度分析

  • 时间复杂度:\(O(n)\),其中 \(n\) 是链表的长度。
  • 空间复杂度:\(O(1)\)
posted @ 2020-11-20 22:25  大杂草  阅读(192)  评论(0编辑  收藏  举报