234. 回文链表
思路:快慢指针,找到中间的节点,然后将中间节点后面的(slow.next)全部reverse,然后依次比较。
注意,reverse的是slow.next后面的。
AC code。
javascript
/**
* 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) {
if(head == null || head.next==null) return true;
// ListNode dummy = new ListNode();
// dummy.next = head;
// head = dummy;
ListNode fast=head, slow=head, slowpre = head;
while(fast.next!=null && fast.next.next!=null){
System.out.println("执行快慢指针时slow=" + slow.val );
fast = fast.next.next;
slowpre = slow;
slow = slow.next;
}
System.out.println("执行快慢指针后slow=" + slow.val );
ListNode half = reverse(slow.next); // 这里需要是slow.next
slow = head;
while(half!=null){
//System.out.println("half=" + half.val + " slow="+slow.val);
if(half.val != slow.val)
return false;
half = half.next;
slow = slow.next;
}
return true;
}
public ListNode reverse(ListNode head){
ListNode dummy = new ListNode();
ListNode p = head, r=null;
while(p!=null){
r = p.next;
p.next = dummy.next;
dummy.next = p;
p = r;
}
return dummy.next;
}
}