思路:先找到链表中点,把中点后边的值用头插法翻转,在拿中点前边的值与后边的比较即可。
代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
ListNode p;//快指针
ListNode q;//慢指针
ListNode x;
ListNode y;
p = head;
q = head;
x = null;
y = head;
while((p != null)&&(p.next != null)) {
p = p.next.next;
q = q.next;
}
if ((p!=null)) {
q = q.next;
}
while (q!=null) {
ListNode s;//头插法
s = q.next;
q.next = x;
x = q;
q = s;
}
while (x != null) {
if (x.val != y.val) {
return false;
}
else {
x = x.next;
y = y.next;
}
}
return true;
}
}