题目:Palindrome Linked List
One:
public class Solution {
public boolean isPalindrome(ListNode head) {
if(head == null) {
return true;
}
//1.遍历确定长度
int length = 0;
ListNode p = head;
while(p != null) {
length ++;
p = p.next;
}
p = head;//用完之后, p归位
if(length == 1) {
return true;
}
//2.将后半部分链反转
int half = (length + 1) / 2;
ListNode q = head;
for(int i = 0; i < half; i ++) {
q = q.next;
}
//开始反转
ListNode r = q.next;
q.next = null;
ListNode m;
while(r != null) {
m = r.next;
r.next = q;
q = r;
r = m;
}
//3.依次比较,直到其中一个或者两个链遍历完
while(q != null && p != null) {
if(p.val == q.val) {
q = q.next;
p = p.next;
}else {
return false;
}
}
return true;
}
}
Two:
public boolean isPalindrome(ListNode head) {
ListNode fast = head, slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
if (fast != null) { // odd nodes: let right half smaller
slow = slow.next;
}
slow = reverse(slow);
fast = head;
while (slow != null) {
if (fast.val != slow.val) {
return false;
}
fast = fast.next;
slow = slow.next;
}
return true;
}
public ListNode reverse(ListNode head) {
ListNode prev = null;
while (head != null) {
ListNode next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}
Three:
public class Solution {
public boolean isPalindrome(ListNode head) {
if(head == null) {
return true;
}
ListNode p1 = head;
ListNode p2 = head;
ListNode p3 = p1.next;
ListNode pre = p1;
//find mid pointer, and reverse head half part
while(p2.next != null && p2.next.next != null) {
p2 = p2.next.next;
pre = p1;
p1 = p3;
p3 = p3.next;
p1.next = pre;
}
//odd number of elements, need left move p1 one step
if(p2.next == null) {
p1 = p1.next;
}
else { //even number of elements, do nothing
}
//compare from mid to head/tail
while(p3 != null) {
if(p1.val != p3.val) {
return false;
}
p1 = p1.next;
p3 = p3.next;
}
return true;
}
}