给定一个带有头结点 head 的非空单链表,返回链表的中间结点。 如果有两个中间结点,则返回第二个中间结点。

本文介绍了一种高效的算法,用于找出链表的中间节点及倒数第K个节点,通过快慢指针技巧避免了两次遍历链表的开销,提升了算法效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

例如:

输入:[1,2,3,4,5]
输出:此列表中的结点 3 (序列化形式:[3,4,5])
返回的结点值为 3 。 (测评系统对该结点序列化表述是 [3,4,5])。

输入:[1,2,3,4,5,6]
输出:此列表中的结点 4 (序列化形式:[4,5,6])
由于该列表有两个中间结点,值分别为 3 和 4,我们返回第二个结点。

方法一:或许链表长度,依次向后遍历len/2步

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode middleNode(ListNode head) {
        int steps = size(head)/2;
        ListNode cur = head;
        for(int i = 0;i < steps;i++){
            cur = cur.next;
        }
        return cur;
    }
    public int size(ListNode head){
        int size = 0;
        for(ListNode cur = head;cur != null;cur = cur.next){
            size++;
        }
        return size;
    }
}

方法二:快慢指针

在这里插入图片描述
fast一次向后走两步。
slow一次向后走一步。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode middleNode(ListNode head) {
        if(head == null || head.next == null){
        //只有一个节点或者无节点的时候,直接返回。
            return head;
        }
        ListNode fast = head;
        ListNode slow = head;
        for(ListNode cur = head; cur != null; cur = cur.next){
            fast = fast.next.next;
            slow = slow.next;
            if(fast == null || fast.next == null){
                return slow;
            }
        }
        return slow;
    }
}

输入一个链表,输出该链表中倒数第k个结点。

public class Solution {
    public ListNode FindKthToTail(ListNode head,int k) {
        if(k <=0 || k > size(head) || head == null){
            return null;
        }
        int steps = size(head) - k;
        ListNode cur = head;
        for(int i = 0;i < steps;i++){
            cur = cur.next;
        }
        return cur;
    }
    public int size(ListNode head){
        int size = 0;
        for(ListNode cur = head;cur != null;cur = cur.next){
            size++;
        }
        return size;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值