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?
思路:快慢指针找到中点,同时修改前一半链表的.next,然后从中间开始向链表两端比较。
/**
* 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;
}
ListNode s = head;
ListNode f = head.next;
ListNode p = null;
ListNode q = f;
while(f != null && f.next != null) {
f = f.next.next;
s.next = p;
p = s;
s = q;
q = q.next;
}
s.next = p;
if(f == null) {
s = s.next;
}
while(s != null && q != null) {
if(s.val != q.val) {
return false;
}
s = s.next;
q = q.next;
}
return s == null && q == null;
}
}