判斷迴文連結串列

woooow發表於2018-09-16

題目描述:判斷一個普通的連結串列是否是迴文連結串列,要求時間複雜度O(n),空間複雜度O(1)


解決思路:

  • 最簡單的方法是利用棧把連結串列的前半段壓棧,然後出棧與連結串列的後半段逐個比對。找中間位置的方法是快慢指標。
  • 還有一種方法是利用快慢指標找到中間,然後將連結串列的後半部分反轉,再依次進行比較,利用的是連結串列反轉的知識。
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;


public class Main_ {

    class ListNode{
        public int val;
        ListNode next = null;

        public ListNode(int val){
            this.val = val;
        }
    }

    //利用棧的思想
    public boolean checkPalindrom(ListNode node){
        if(node == null)
            return false;
        Stack<ListNode> stack = new Stack<>();
        ListNode fast = node;
        ListNode slow = node;
        while (fast != null && fast.next != null){
            stack.push(slow);
            slow = slow.next;
            fast = fast.next.next;
        }
        //如果為奇數個
        if(fast != null)
            slow = slow.next;
        while (!stack.isEmpty()){
            if(stack.pop().val != slow.val)
                return false;
            slow = slow.next;
        }

        return true;
    }

    //利用連結串列反轉的思想
    public boolean checkPalindrom_(ListNode node){
        if(node == null)
            return false;
        ListNode fast = node;
        ListNode slow = node;
        while (fast != null && fast.next != null){
            slow = slow.next;
            fast = fast.next.next;
        }

        while (fast != null)
            slow = slow.next;
        ListNode p = slow.next;
        ListNode q = slow.next.next;
        slow.next = null;
        while(p != null){
            p.next = slow;
            slow = p;
            p = q;
            if(q.next != null)
                q = q.next;
        }
        while (slow != null){
            if(slow.val != node.val)
                return false;
            slow = slow.next;
            node = node.next;
        }

        return true;
    }

    public static void main(String[] args) {
        ListNode node1 = new Main_().new ListNode(1);
        ListNode node2 = new Main_().new ListNode(2);
        ListNode node3 = new Main_().new ListNode(3);
        ListNode node4 = new Main_().new ListNode(3);
        ListNode node5 = new Main_().new ListNode(1);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = null;
        System.out.println(new Main_().checkPalindrom(node1));
        System.out.println(new Main_().checkPalindrom(node1));
    }
}


相關文章