题目描述
编写一个函数,检查输入的链表是否是回文的。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
class Solution {
public boolean isPalindrome(ListNode head) {
if(head == null || head.next == null){
return true;
}
//找到链表中间点
ListNode low = head;
ListNode fast = head;
while(fast != null && fast.next != null){
low = low.next;
fast = fast.next.next;
}
if(fast != null){//说明有奇数个结点,low需要再走一步。
low = low.next;
}
//翻转后半段链表
ListNode cur = low.next;
low.next = null;
while(cur != null){
ListNode temp = cur.next;
cur.next = low;
low = cur;
cur = temp;
}
//比较前后段是否一致
while(low != null){
if(low.val != head.val){
return false;
}
low = low.next;
head = head.next;
}
return true;
}
}