您的位置:首页 > 其它

[LeetCode 234] Palindrome Linked List

2015-08-18 14:38 471 查看
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?
Solution:
1. Reverse later half part

2. two pointer go through list, one from front and end

public boolean isPalindrome(ListNode head) {
        if(head ==null || head.next == null) return true;
        //get middle node, 
        ListNode l1 = head;
        ListNode l2 = head;
        while(l2.next!=null){
            l1 = l1.next;
            if(l2.next.next == null){
                l2 = l2.next;
                break;
            }
            l2 = l2.next.next;
        }
        //reverse linked list
        l2 = l1.next;
        while(l2!=null) {
            ListNode l3 = l2.next;
            l2.next = l1;
            l1 = l2;
            l2 = l3;
        }//l1 is the last one
        //two pointer from front and end
        l2 = head;
        while(l2 != l1 && l2.next!=l1){
            if(l1.val != l2.val)
                return false;
            l1 = l1.next;
            l2 = l2.next;
        }
        if(l2.next == l1) return l2.val == l1.val;
        return true;
    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: