判斷單鏈表是否是迴文結構的3種方法

  • 問題描述
    判斷單鏈表是否是迴文結構。

  • 解決方案1
    將鏈表中的數據全部壓入堆棧,然後再依次彈出和原來的鏈表進行對比。

  /**
     * 全部壓棧,然後依次彈出對比
     * @param head
     * @return
     */
    public static boolean isPalindrome1(Node head){
        Node cur = head;
        Stack<Integer> stack = new Stack<>();
        while(cur != null){
            stack.push(cur.value);
            cur = cur.next;
        }
        cur = head;
        while(cur != null){
            if(cur.value != stack.pop())
                return false;
            cur = cur.next;
        }
        return true;
    }

  • 解決方案2
    首先利用快慢指針找到鏈表的中間位置,將後半部分壓棧,然後再依次彈出和原來的鏈表進行對比。
   /**
     * 後半部分壓棧,然後依次彈出對比
     * @param head
     * @return
     */
    public static boolean isPalindrome2(Node head){
        //首先利用快慢指針找鏈表中點
        Node slow = head;
        Node fast = head;

        while(fast.next != null && fast.next.next!=null){
            slow = slow.next;
            fast = fast.next.next;
        }
        Node cur = slow.next;
        Stack<Integer> stack = new Stack<>();
        while(cur != null){
            stack.push(cur.value);
            cur = cur.next;
        }
        cur = head;
        while(!stack.isEmpty()){
            if(stack.pop() != cur.value)
                return false;
            cur = cur.next;
        }
        return true;
    }

  • 解決方案3
    首先利用快慢指針找到鏈表的中間位置,然後將鏈表後半部分逆序,最後將鏈表的後半部分和前半部分依次對比,看是否一樣。
 /**
     * 前半部分壓棧,後半部分逆序,然後對比
     * @param head
     * @return
     */
    public static boolean isPalindrome3(Node head){
        //首先利用快慢指針找鏈表中點
        Node slow = head;
        Node fast = head;

        while(fast.next != null && fast.next.next!=null){
            slow = slow.next;
            fast = fast.next.next;
        }
        Node cur = slow.next;

        cur = invertLinkedList(cur);
        while(cur != null){
            if(cur.value != head.value)
                return false;
            cur = cur.next;
            head = head.next;
        }
        return true;
    }

    //逆序單鏈表
    public static Node invertLinkedList(Node head){
        Node res;
        if(head == null)
            return null;
        res = head;
        Node cur = head.next;
        head.next = null;//鏈表結尾置爲空
        while(cur != null){
            Node temp = cur;
            cur = cur.next;
            temp.next = res;
            res = temp;
        }
        return res;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章