码迷,mamicode.com
首页 > 其他好文 > 详细

234. Palindrome Linked List

时间:2016-04-14 14:10:38      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:

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?

 

Subscribe to see which companies asked this question

 
 
ArrayDeque Solution :
/**
 * 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;
        
        Deque<Integer> items = new ArrayDeque<Integer>();
        ListNode h = head;
        while(h != null)
        {
            items.add(h.val);
            h = h.next;
        }
        
        while(items.size()>1){
            Integer headVal = items.remove();
            Integer tailVal = items.removeLast();
            if(headVal != tailVal)
                return false;
            
        }
        
        return true;
    }
}

 

 
 
 
O(n) time and O(1) space solution. Split the linked list into to two linked list. One from head to middle, the other from tail to middle.
/**
 * 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;
        
        int l = -1;
        ListNode h = head;
        while(h != null) {
            ++l;
            h = h.next;
        }
        int middle = l/2;
        
        h = head;
        while(middle>0)
        {
            --middle;
            h = h.next;
        }
        
        ListNode h2 = h.next;
        h.next = null; //h points to end of first part
        
        ListNode tail = revertList(h2);
        h = head;
        while(h!=null && tail!= null)
        {
            if(h.val != tail.val)
                return false;
            h = h.next;
            tail = tail.next;
        }
        
        return true;
    }
    
    private ListNode revertList(ListNode head)
    {
        if(head == null || head.next == null)
            return head;
            
        ListNode h1 = head;
        ListNode h2 = head.next;
        while(h2 != null)
        {
            ListNode h2next = h2.next;
            h2.next = h1;
            h1 = h2;
            h2 = h2next;
        }
        head.next = null;
        return h1;
    }
}

 

 
 
 
 

234. Palindrome Linked List

标签:

原文地址:http://www.cnblogs.com/neweracoding/p/5390719.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!