【链表】快慢指针的边界问题

在对链表进行操作时我们经常用到快慢指针,针对不同的场景会有不同的边界要求:

  • 奇数长度返回中点,偶数长度返回上中点
public static Node upMid(Node head) {
    if (head == null) {
        return null;
    }
    Node slow = head;
    Node fast = head;
    if (fast.next != null && fast.next.next != null) {
        slow = slow.next;
        fast = fast.next.next;
    }
    return slow;
}
  • 奇数长度返回中点,偶数长度返回下中点
public static Node downMid(Node head) {
    if (head == null || head.next == null) {
        return head;
    }
    Node slow = head;
    Node fast = head.next;
    while (fast.next != null && fast.next.next != null) {
        slow = slow.next;
        fast = fast.next.next;
    }
    return slow.next;
}
  • 奇数长度返回中点前一个,偶数长度返回上中点前一个
public static Node preOfUpMid(Node head) {
    if (head == null || head.next == null || head.next.next == null) {
        return null;
    }
    Node slow = head;
    Node fast = head.next.next;
    while (fast.next != null && fast.next.next != null) {
        slow = slow.next;
        fast = fast.next.next;
    }
    return slow;
}
  • 奇数长度返回中点前一个,偶数长度返回下中点前一个
public static Node preOfDownMid(Node head) {
    if (head == null || head.next == null) {
        return null;
    }
    Node slow = head;
    Node fast = head.next;
    while (fast.next != null && fast.next.next != null) {
        slow = slow.next;
        fast = fast.next.next;
    }
    return slow;
}
  • 奇数长度返回中点下一个,偶数长度返回上中点下一个
public static Node afterOfUpMid(Node head) {
    if (head == null || head.next == null) {
        return null;
    }
    Node slow = head.next;
    Node fast = head;
    while (fast.next != null && fast.next.next != null) {
        slow = slow.next;
        fast = fast.next.next;
    }
    return slow;
}
  • 奇数长度返回中点下一个,偶数长度返回下中点下一个
public static Node afterOfDownMid(Node head) {
    if (head == null || head.next == null || head.next.next == null) {
        return null;
    }
    Node slow = head.next.next;
    Node fast = head.next;
    while (fast.next != null && fast.next.next != null) {
        slow = slow.next;
        fast = fast.next.next;
    }
    return slow.next;
}
posted @   hzyuan  阅读(96)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)

喜欢请打赏

扫描二维码打赏

支付宝打赏

点击右上角即可分享
微信分享提示