您的位置:首页 > 其它

234. Palindrome Linked List

2016-04-14 13:20 260 查看

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?

Linked List Two Pointers

With extra space, add everything to a list first and then compare.

/**
* 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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: