234 Palindrome Linked List

题目要求在O(n)时间和O(1)空间内判断一个链表是不是回文的。
先将链表分成2部分,然后反转其中一个,在进行比较。

/** * 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) {

        if(head==null||head.next==null)
            return true;

        ListNode half=CutHalf(head);
        half=Reserve(half);

        while(head!=null&&half!=null){
            if(head.val!=half.val)
                return false;
            head=head.next;
            half=half.next;
        }
        return true;
    }

    public ListNode CutHalf(ListNode head) {

        ListNode p = head;

        while (p.next != null && p.next.next != null) {
            p = p.next.next;
            head = head.next;
        }

        p = head.next;
        head.next = null;
        return p;
    }

    public ListNode Reserve(ListNode head){

        ListNode list = null;
        ListNode p;

        while(head!=null){

            p=head;
            head=head.next;

            p.next=list;
            list=p;
        }

        return list;
    }
}

你可能感兴趣的:(链表,回文)