翻转first half 然后一个从中间向前 一个向后 进行对比
我自己写的把找到中间和翻转写成了两步 很多错 很麻烦 其实可以写到一起
public class Solution {
public boolean isPalindrome(ListNode head) {
if ( head == null || head.next == null )
return true;
ListNode fast = head;
ListNode slow = head;
ListNode pre = new ListNode (0);
pre.next = head;
while ( fast != null && fast.next != null ){
fast = fast.next.next;
slow = slow.next;
pre = pre.next;
}
ListNode second = slow;
if ( fast != null ){
second = second.next;
}
slow = pre;
ListNode cur = head.next;
ListNode pre2 = head;
head.next = null;
while ( pre2 != slow ){
ListNode temp = cur.next;
cur.next = pre2;
pre2 = cur;
cur = temp;
}
while ( second != null && pre2 != null ){
if ( second.val != pre2.val )
return false;
pre2 = pre2.next;
second = second.next;
}
return true;
}
}
写到一起的方法
public class Solution {
public boolean isPalindrome(ListNode head) {
if ( head == null || head.next == null )
return true;
ListNode fast = head;
ListNode slow = head;
ListNode pre = new ListNode (0);
pre.next = head;
while ( fast != null && fast.next != null ){
fast = fast.next.next;
ListNode temp = slow.next;
slow.next = pre;
pre = slow;
slow = temp;
}
ListNode second = slow;
if ( fast != null ){
second = second.next;
}
slow = pre;
while ( second != null && slow != null ){
if ( second.val != slow.val )
return false;
slow = slow.next;
second = second.next;
}
return true;
}
}