234--Palindrome Linked List

public class PalindromeLinkedList {
    /*
    解法一:可能刚开始刷题的原因,想到的老是这种简单的笨办法。
     */

    public static boolean isPalindrome(ListNode head) {
        if(head==null||head.next==null)
            return true;
        ListNode temp=head;
        List<Integer> list=new ArrayList<>();
        while (temp!=null){
            list.add(temp.val);
            temp=temp.next;
        }
        temp=head;
        for (int i=list.size()-1;i>=0;i--){
            if (temp.val!=list.get(i).intValue())
                return false;
            temp=temp.next;
        }
        return true;
    }

   
    /*
    解法二:用快慢指针找到链表中点,同时反转前半部分,然后依次从中点向两边回文检验。
     */
    public boolean isPalindrome2(ListNode head) {
        if (head==null||head.next==null)
            return true;
        ListNode slow=head;
        ListNode fast=head.next;
        ListNode previous=null;
        ListNode next=null;
        while (fast!=null&&fast.next!=null){
            next=slow.next;
            slow.next=previous;
            previous=slow;
            slow=next;
            fast=fast.next.next;
        }
        ListNode right=slow.next;
        ListNode left=null;
        if (fast==null)
            left=previous;
        else{
            slow.next=previous;
            left=slow;
        }
        while (left!=null){
            if (left.val!=right.val)
                return false;
            left=left.next;
            right=right.next;
        }
        return true;
    }
}

 

posted @ 2019-09-01 10:23  张玉昊  阅读(278)  评论(0编辑  收藏  举报