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?
public class Solution234 {
public boolean compare(ListNode ans1, ListNode ans2) {
for (; ans2 != null && ans1 != null;ans1 = ans1.next, ans2 = ans2.next) {
if(ans1.val != ans2.val) {
return false;
}
}
if(ans1 == null && ans2 == null) {
return true;
}
return false;
}
public void print(ListNode tmp) {
for (; tmp!=null; tmp = tmp.next) {
System.out.print(tmp.val + " ");
}
System.out.println();
}
public boolean isPalindrome(ListNode head) {
int len = 0, position = 0;
for (ListNode tmp = head; tmp != null; tmp = tmp.next) {
len++;
}
if(len < 2) {
return true;
}
if(len%2 == 0) {
position = len/2;
}else {
position = len/2+1;
}
ListNode ans1 = head;
for (int i = 1; i <= position; i++) {
ans1 = ans1.next;
}
//print(ans1);
if(len%2 == 1) {
position -= 1;
}
ListNode pre = null, cur =head, next = head;
for (int i = 0; i < position; i++) {
next = next.next;
cur.next = pre;
pre = cur;
cur = next;
}
cur = pre;
//print(cur);
return compare(cur, ans1);
}
public static void main(String[] args) {
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(2);
head.next.next.next.next = new ListNode(1);
Solution234 ans = new Solution234();
System.out.println(ans.isPalindrome(head));
}
}