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;
}
}
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;
}
}
相关文章推荐
- Leetcode Compare Version Numbers
- Leetcode Insertion Sort List
- Leetcode Unique Binary Search Trees
- Leetcode Linked List Cycle II
- Leetcode Remove Nth Node From End of List
- Leetcode Integer to Roman
- Leetcode Valid Anagram
- Leetcode Single Number II
- 大公司还是小公司(非常全面和有道理,居然还是原创)
- Leetcode Pascal's Triangle
- Leetcode Balanced Binary Tree
- Leetcode Divide Two Integers
- Leetcode Sqrt(x)
- Leetcode Number of Digit One
- Leetcode Largest Number
- Leetcode Word Break II
- [leetcode] 118. Pascal's Triangle
- php判断是否为今天
- Codeforces Round #327 (Div. 2)
- 决策树算法(四)——选取最佳特征划分数据集