请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
**先用快慢指针确定链表的中间位置
对后半部分链表进行翻转
从头尾开始比较判断
**
class Solution {
public boolean isPalindrome(ListNode head) {
ListNode fast, slow;
fast = head;
slow = head;
while(fast.next != null && fast.next.next != null){
fast = fast.next.next;
slow = slow.next;
}
ListNode tail = reverseList(slow.next);
ListNode end = tail;
boolean result = true;
while(result && end != null){
if(end.val != head.val)
result = false;
head = head.next;
end = end.next;
}
return result;
}
private ListNode reverseList(ListNode head){
ListNode pre = null;
ListNode cur = head;
while(cur != null){
ListNode temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
}