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

思路:stack存数,然后从头比较。

/**
 * 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;
        }
        Stack<Integer> check=new Stack<Integer>();
        ListNode copy=head;
        while(copy!=null)
        {
            check.push(copy.val);
            copy=copy.next;
        }
        while(head!=null)
        {
            if(head.val!=check.pop())
            {
                return false;
            }
            head=head.next;
        }
        return true;
        
    }
}

Solution2:

Follow up:  O(n) in time, O(1) in space.

思路:用reverse linkedlist 做。快慢指针找到中点,然后切割。reverse后半段,再从头判断。注意快指针的边界条件!!!

/**
 * 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 mid=head;
        ListNode slow=head;
        ListNode fast=head;
        while(fast!=null&&fast.next!=null)
        {
            mid=slow;
            slow=slow.next;
            fast=fast.next.next;
        }
        if(fast==null)
        {
            mid.next=null;
        }
        else
        {
            mid.next=null;
            slow=slow.next;
        }
        ListNode check=reverseList(slow);
        while(head!=null&&check!=null)
        {
            if(head.val!=check.val)
            {
                return false;
            }
            head=head.next;
            check=check.next;
        }
        return true;
        
    }
        public ListNode reverseList(ListNode head) {
        if(head==null)
        {
            return head;
        }
        ListNode dummy=new ListNode(-1);
        if(head.next!=null)
        {
            ListNode copy=head.next;
            dummy.next=reverseList(head.next);
            copy.next=head;
            head.next=null;
        }
        else
        {
            return head;
        }
        return dummy.next;
        
    }
}

 

posted on 2016-09-13 08:54  Machelsky  阅读(109)  评论(0)    收藏  举报