给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。
示例 1:
输入:head = [1,2,2,1]
输出:true
示例 2:
输入:head = [1,2]
输出:false
提示:
链表中节点数目在范围[1, 105] 内
0 <= Node.val <= 9
进阶:你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
/**
* 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 fast = head, slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
//奇数,确保slow是后半段
if (fast != null) slow = slow.next;
ListNode reverseNode = reverse(slow);
while (reverseNode != null) {
if (reverseNode.val != head.val) return false;
reverseNode = reverseNode.next;
head = head.next;
}
return true;
}
private ListNode reverse(ListNode head) {
ListNode pre = null;
while (head != null) {
ListNode next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
}
递归
class Solution {
ListNode pre;
public boolean isPalindrome(ListNode head) {
pre = head;
return recur(head);
}
private boolean recur(ListNode head) {
if (head == null) return true;
if (!recur(head.next)) return false;
if (pre.val != head.val) return false;
pre = pre.next;
return true;
}
}