判断链表是否是回文链表

给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。

public static class Node{
    public int value;
    public Node next;
    public Node(int data){
        value = data;
    }
}
  1. 使用栈做辅助空间,额外需要n个空间

public static boolean isPalindromeList1(Node head){
    Stack stack = new Stack<>();
    Node cur = head;
    while(cur != null){
        stack.push(cur);
        cur = cur.next;
    }
    while(head != null){
        if(head.value == stack.pop().value){
            head = head.next;
        }else {
            return false;
        }
    }
    return true;
}
  1. 使用栈做辅助空间,额外需要n/2个空间

public static boolean isPalindromeList2(Node head){
    if(head == null || head.next == null){
        return true;
    }
    Node slow = head;
    Node fast = head.next;
    while(fast.next != null && fast.next.next != null){
        slow = slow.next;
        fast = fast.next.next;
    }
    Stack stack = new Stack<>();
    while(slow != null){
        stack.push(slow);
        slow = slow.next;
    }
    while(!stack.isEmpty()){
        if(head.value == stack.pop().value){
            head = head.next;
        }else {
            return false;
        }
    }
    return true;
}
  1. 不使用额外辅助空间,运用链表翻转判断回文链表,空间复杂度O(1)

public static boolean isPalindromeList3(Node head){
    if(head == null || head.next == null){
        return true;
    }
    Node n1 = head;
    Node n2 = head;
    while(n2.next != null && n2.next.next != null){
        n1 = n1.next;   // n1->mid
        n2 = n2.next.next;  // n2->end
    }

    n2 = n1.next;   // n2 -> right part first node
    n1.next = null; // mid.next -> null
    Node n3 = null;
    while(n2 != null){  // 右侧链表翻转
        n3 = n2.next;   // n3 -> save next node
        n2.next = n1;   // next of right node convert
        n1 = n2;    // n1 move
        n2 = n3;    // n2 move
    }
    n3 = n1;    // n3 -> save last node
    n2 = head;  // n2 -> left first node
    boolean res = true;
    while(n1 != null && n2 != null){    // 检查是否是回文链表
        if(n1.value != n2.value){
            res = false;
            break;
        }
        n1 = n1.next;   // left to mid
        n2 = n2.next;   // right to mid
    }
    n1 = n3.next;
    n3.next = null;
    while(n1 != null){  // recover list
        n2 = n1.next;
        n1.next = n3;
        n3 = n1;
        n1 = n2;
    }
    return res;
}

你可能感兴趣的:(算法学习,链表,数据结构)