原题链接: https://leetcode.com/problems/middle-of-the-linked-list/
1. 题目介绍
Given a non-empty, singly linked list with head node head, return a middle node of linked list. If there are two middle nodes, return the second middle node.
给定一个非空单向链表,返回这个链表的中点。如果这个链表的节点数为偶数,就返回最中间的2个节点中后面的那个。
Example 1:
Input: [1,2,3,4,5]
Output: Node 3 from this list (Serialization: [3,4,5])
The returned node has value 3. (The judge's serialization of this node is [3,4,5]).
Note that we returned a ListNode object ans, such that:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NULL.
Example 2:
Input: [1,2,3,4,5,6]
Output: Node 4 from this list (Serialization: [4,5,6])
Since the list has two middle nodes with values 3 and 4,
we return the second one.
Note:
The number of nodes in the given list will be between 1 and 100.
链表的节点数范围是[ 1 , 100 ].
2. 解题思路
找出链表的中点,可以使用双指针法。
使用一个快指针 fast ,一个慢指针 slow ,一开始 fast 和 slow 都指向链表的头节点。然后 fast 每次走 2 步,slow 每次走 1 步,这样当 fast 走到链表的结尾时,slow 就会走到链表的中间。
1 . 对于长度为奇数的链表:
以 1-> 2 -> 3 -> 4 -> 5 为例 ,fast 依次指向 1,3,5,当 fast 指向 5 的时候,slow 恰好指向 3,正好是链表的中点。此时结束遍历的条件是 fast.next = null。
为什么不是继续让 fast 等于 null 后再结束遍历呢?是因为 fast 的下一步没有办法继续走下去了(fast.next.next 已经为null了)
2. 对于长度为偶数的链表:
以 1-> 2 -> 3 -> 4 -> 5 -> 6 为例,fast 依次指向1,3,5 和 null。当 fast 指向 null 的时候,结束遍历,此时slow 指向 4 ,这就是我们要返回的点。
所以综合来看,遍历链表结束的条件应该是
fast != null && fast.next != null
时间复杂度为 O(n)
空间复杂度为O(1)
具体实现代码如下所示:
实现代码
class Solution {
public ListNode middleNode(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
}
return slow;
}
}