/**
* 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 p2 = getMiddleNode(head);
p2 = reverseListNode(p2);
ListNode p1 = head;
while (p2 != null) {
if (p1.val != p2.val) {
return false;
}
p1 = p1.next;
p2 = p2.next;
}
return true;
}
public ListNode getMiddleNode(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode p1 = head;
ListNode p2 = head;
while (p2 != null) {
if (p2.next != null) {
p2 = p2.next.next;
p1 = p1.next;
} else {
p2 = p2.next;
}
}
return p1;
}
public ListNode reverseListNode(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode last = reverseListNode(head.next);
head.next.next = head;
head.next = null;
return last;
}
}
新年快乐家人们,希望大家每天都能开心,事业有成,顺顺利利