[leedcode 234] Palindrome Linked List

Given a singly linked list, determine if it is a palindrome.

Follow up:
Could you do it in O(n) time and O(1) space?

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isPalindrome(ListNode head) {
        /*判断给定的链表是不是回文的:

        把要判断的链表分成两部分,将第二部分逆置,逐个与前一部分的val相比较,若不同返回false*/
        
        if(head==null||head.next==null) return true;
        ListNode fast=head;
        ListNode slow=head;
        while(fast!=null&&fast.next!=null){//假如链表有奇数个元素,则slow指针在循环后指向正中的元素;
        //若链表有偶数个元素,则循环后slow指向n/2的元素位置
            fast=fast.next.next;
            slow=slow.next;
        }
        ListNode list2=reverse(slow);//将链表后面逆置
        while(list2!=null){
            if(head.val!=list2.val) return false;
            head=head.next;
            list2=list2.next;
        }
        return true;
    }
    public ListNode reverse(ListNode node){
        ListNode pre=null;
        ListNode p=node;
        ListNode rear=node;
        while(rear!=null){
            rear=rear.next;
            p.next=pre;
            pre=p;
            p=rear;
        }
        return pre;
    }
}

 

posted @ 2015-08-08 18:04  ~每天进步一点点~  阅读(104)  评论(0编辑  收藏  举报