請判斷一個連結串列是否為迴文連結串列。

Richal發表於2018-09-03
public class BackLink {
    public static void main(String[] args) {
        ListNode one = new ListNode(1);
        ListNode two = new ListNode(1);
        ListNode three = new ListNode(2);
        ListNode four = new ListNode(1);
//        ListNode five = new ListNode(3);
//        ListNode six = new ListNode(2);
//        ListNode seven = new ListNode(1);
        one.next = two;
        two.next = three;
        three.next = four;
        four.next = null;
//        five.next = six;
//        six.next = seven;
//        seven.next = null;
        printLink(one);
        System.out.println(BackLink(one));
    }

    public static void printLink(ListNode head) {
        if (null == head) System.out.println("head is null");
        while (head != null) {
            System.out.println(head.val);
            head = head.next;
        }

    }

    public static boolean BackLink(ListNode head) {
        if (head == null || head.next == null) return true;
        ListNode middleNode = getMiddleNode(head);
        middleNode.next = reverseListNode(middleNode.next);
        ListNode p = head, q = middleNode.next;
        if (q == null && p.val==p.next.val)return true;
        if (q==null){
            if (p.val == p.next.val) return  true;
            return false;
        }
        while (p != null && q != null) {
            if (p.val == q.val) {
                p = p.next;
                q = q.next;
            } else {
                break;
            }
        }
        return q == null;
    }

    //根據快慢指標 查詢中間位置
    public static ListNode getMiddleNode(ListNode head) {
        if (null == head || head.next == null) return head;
        ListNode p = head, q = head;
        while (p != null && p.next != null) {
            p = p.next.next;
            if (p == null) return q;
            q = q.next;
        }
        return q;
    }

    public static ListNode reverseListNode(ListNode head) {
        if (head == null) return head;
        ListNode prev = null;
        while (head != null) {
            ListNode temp = head.next;
            head.next = prev;
            prev = head;
            head = temp;
        }
        return prev;
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }
}複製程式碼


相關文章