LeetCode-234. 回文链表
/**
* 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 fast = head;
ListNode slow = head;
while(fast.next!=null && fast.next.next!=null){
fast = fast.next.next;
slow = slow.next;
}
slow = reverse(slow.next);
while(slow!=null){
if(head.val != slow.val){
return false;
}
head=head.next;
slow=slow.next;
}
return true;
}
private ListNode reverse(ListNode head){
ListNode pre=null;
while(head!=null){
ListNode tmp = head.next;
head.next=pre;
pre = head;
head = tmp;
}
return pre;
}
}