[Leetcode学习]Middle of the Linked List(获取链表中间节点)

我的代码:

验证链表环的时候,使用过快慢指针,这时候就是见证数学公式的能力了。

class Solution {
    public ListNode middleNode(ListNode head) {
        // 慢指针指向head内存地址
        ListNode slow = head;
        
        // 双判断head是否null
        while(head != null) {
            head = head.next;

            // 只有head走第二步时候,slow才走
            if(head != null) {
                head = head.next;
                slow = slow.next;
            }
        }
        
        // 无论刚传入head是null或者head.next是null,都是正确的
        return slow;
    }
}

问题:

难度easy

链表环快慢指针问题:https://blog.csdn.net/qq_28033719/article/details/104853725

输入输出案例:

// 输入12345,返回3,3是中间节点
Input: [1,2,3,4,5]
Output: Node 3 from this list (Serialization: [3,4,5])

// 输入123456,双数位时候,返回4,3和4都算是中间位,返回后面4
Input: [1,2,3,4,5,6]
Output: Node 4 from this list (Serialization: [4,5,6])

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值