您的位置:首页 > 其它

Leetcode Palindrome Linked List

2016-07-19 05:05 204 查看
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?

Difficulty: Easy

<pre name="code" class="java">/**
* 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 count = 0;
ListNode curr = head;
ListNode left = head, right = head, next = right.next;
while(curr != null){
count++;
curr = curr.next;
}
if(count%2 == 1){
for(int i = 0; i < count/2 - 1; i++){
left = right;
right = next;
next = right.next;
right.next = left;
}
left = right;
right = next.next;
}
else{
for(int i = 0; i < count/2 - 1; i++){
left = right;
right = next;
next = right.next;
right.next = left;
}
left = right;
right = next;
}

while(left != null && right != null){
if(left.val != right.val){
return false;
}
left = left.next;
right = right.next;
}
return true;
}
}


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: