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 Solution {
public boolean isPalindrome(ListNode head) {
if(head==null || head.next==null){ //最多一个节点
return true;
}
else{ //至少三个节点
ListNode p=head;
int count=0; //记录链表的总结点个数
while(p!=null){
count++;
p=p.next;
}
//然后再从头结点开始,利用头插法,形成前一半count节点的链表
p=head.next;
ListNode t=head; //前一半链表的头节点
int fircount=1;
while(fircount<count/2){
ListNode q=p;
p=p.next;
q.next=t;
t=q;
fircount++;
}
//while结束后,p指向后一半链表的第一个节点
//t一直指向前一半链表的head
if(count%2!=0){ //原链表个数为奇数时,跳过中间的那个节点
p=p.next;
}
while(t!=null && p!=null){
if(t.val!=p.val){
return false;
}
t=t.next;
p=p.next;
}
return true;
}
}
}