目录
1.题目描述
给定一个头结点为 head
的非空单链表,返回链表的中间结点。
如果有两个中间结点,则返回第二个中间结点。
题目来源:力扣(LeetCode)
2.解法
定义一个快指针 fast 和一个慢指针 slow ;fast 走两步, slow 走一步,当 fas t走到尽头时,
slow 就刚好在中间节点。因为 fast 比slow 多走一半路程
class Solution {
public ListNode middleNode(ListNode head) {
if (head == null) {
return null;
}
ListNode fast = head;
ListNode slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
return slow;
}
}
3.复杂度
复杂度分析
时间复杂度:O(N),其中 N 是给定链表的结点数目。
空间复杂度:O(1),只需要常数空间存放 slow 和 fast 两个指针