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

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

  • 奇数长度返回中点,偶数长度返回上中点
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 @ 2022-01-18 23:49  hzyuan  阅读(117)  评论(0)    收藏  举报