标签:
Follow up:
Could you do it in O(n) time and O(1) space?
Subscribe to see which companies asked this question
/** * 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; } }
/** * 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; } }
标签:
原文地址:http://www.cnblogs.com/neweracoding/p/5390719.html