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?
思想:转置后半段链表节点,然后比较前半段和后半段节点的值是否相等。
代码如下:
/** * 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 len=0,tmp=0; ListNode p=head,q=head,r=head,s=head; int m1=0,m2=0; int n1=0,n2=0; while(p!=null){ len++; p=p.next; } if(len==2){ if(head.val==head.next.val) return true; else return false; } p=head; if(len%2==1){ m1=0; m2=len/2+1; n1=m2-2; n2=len-1; }else{ m1=0; m2=len/2; n1=m2-1; n2=len-1; } while(p!=null && tmp!=m2){ p=p.next; tmp++; } //p到达转置数组的头部 q=p; if(p.next!=null){ q=p; p=p.next; q.next=null; while(p!=null){ r=p.next; p.next=q; q=p; p=r; }//while 循环后,q指后半段头 } while(q!=null &&s.val==q.val){ q=q.next;s=s.next; } if(q==null) return true; else return false; } }
运行结果: