public static boolean isPalindrome(ListNode head) {
if((head == null) || (head!=null && head.next == null)) {
return true;
}
int count = 0;
ListNode cur = head;
while(cur != null) {
count++;
cur = cur.next;
}
int needProcess = (count%2 == 0?count/2:count/2+1);
int i = 1;
cur = head;
while(i < needProcess) {
i++;
cur = cur.next;
}
ListNode pre = cur.next,thead = null,tcur = pre.next,tn = null;
pre.next = null;
while(tcur != null) {
tn = tcur.next;
tcur.next = pre;
pre = tcur;
tcur = tn;
}
thead = pre;
boolean is = true;
tcur = head;
while(thead != null && tcur != null) {
if(thead.val != tcur.val) {
is = false;
break;
}
thead = thead.next;
tcur = tcur.next;
}
tcur = pre.next;
pre.next = null;
tn = null;
while(tcur!= null) {
tn = tcur.next;
tcur.next = pre;
pre = tcur;
tcur = tn;
}
cur.next = pre;
return is;
}
234. Palindrome Linked List
最新推荐文章于 2024-10-13 15:10:00 发布