题目:
请检查一个链表是否为回文链表。
进阶-----你能在 O(n) 的时间和 O(1) 的额外空间中做到吗?
链表用到了快慢指针,快指针每次跳两下,慢指针每次跳一下,这样快指针到终点的时候慢指针刚好一般,然后反转后半部分链表进行对比。该方法时间复杂度O(n)、空间复杂度O(1).
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
if(head==null || head.next==null){
return true;
}
ListNode slow=head,fast=head;
while((fast.next!=null) && (fast.next.next!=null)){
slow=slow.next;
fast=fast.next.next;
}
ListNode last=slow.next,pre=head;
while(last.next!=null){
ListNode tmp=last.next;
last.next=tmp.next;
tmp.next=slow.next;
slow.next=tmp;
}
while(slow.next!=null){
slow=slow.next;
if(pre.val!=slow.val)return false;
pre=pre.next;
}
return true;
}
}