[LeetCode] 876. Middle of the Linked List

32 篇文章 0 订阅
19 篇文章 0 订阅

原题链接: 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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值