链表相关面试题

137 阅读2分钟

快慢指针

  1. 输入链表头结点,奇数长度返回中点,偶数长度返回上中点
//输入链表头结点,奇数长度返回中点,偶数长度返回上中点
public static Node midOrUpMidNode(Node head) {
    if (head == null || head.next == null || head.next.next == null) {
        return head;
    }
    //链表有三个或三个以上的节点
    Node slow = head.next;
    Node fast = head.next.next;
    while (fast.next != null && fast.next.next != null) {
        slow = slow.next;
        fast = fast.next.next;
    }
    return slow;
}
  1. 输入链表头结点,奇数长度返回中点,偶数长度返回下中点
//输入链表头结点,奇数长度返回中点,偶数长度返回下中点
public static Node midOrDownMidNode(Node head) {
    if (head == null || head.next == null) {
        return head;
    }
    //链表有两个或两个以上的节点
    //slow和fast都来到第二个节点的位置
    Node slow = head.next;
    Node fast = head.next;
    while (fast.next != null && fast.next.next != null) {
        slow = slow.next;
        fast = fast.next.next;
    }
    return slow;
}
  1. 输入链表头结点,奇数长度返回中点前一个,偶数长度返回上中点前一个
//输入链表头结点,奇数长度返回中点前一个,偶数长度返回上中点前一个
public static Node midOrUpMidPreNode(Node head) {
    if (head == null || head.next == null || head.next.next == null) {
        return head;
    }
    //链表有三个或三个以上的节点
    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;
}
  1. 输入链表头结点,奇数长度返回中点前一个,偶数长度返回下中点前一个
//输入链表头结点,奇数长度返回中点前一个,偶数长度返回下中点前一个
public static Node midOrDownMidPreNode(Node head) {
    if (head == null || head.next == null) {
        return head;
    }
    //链表有两个或两个以上的节点
    //slow和fast都来到第二个节点的位置
    Node slow = head;
    Node fast = head.next;
    while (fast.next != null && fast.next.next != null) {
        slow = slow.next;
        fast = fast.next.next;
    }
    return slow;
}

链表回文

//给定一个单链表的头结点head,请判断该链表是否为回文结构
//1)把链表放到stack,stack出栈相当于逆序,逆序和正序一样就是回文结构
public static boolean isPalindrome1(Node head) {
    Stack<Node> stack = new Stack<>();
    Node cur = head;
    while (cur != null) {
        stack.push(cur);
        cur = cur.next;
    }
    cur = head;
    while (cur != null) {
        if (cur.data != stack.pop().data) {
            return false;
        }
        cur = cur.next;
    }
    return true;
}