Python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def isPalindrome(self, head: Optional[ListNode]) -> bool:
res = list()
cur = head
while cur:
res.append(cur.val)
cur = cur.next
i, j = 0, len(res)-1
while i <= j:
if res[i] != res[j]:
return False
i += 1
j -= 1
return True
Java
法1:递归,O(N) + O(N)
class Solution {
ListNode left; // 标记左侧TreeNode
public boolean isPalindrome(ListNode head) {
if (head == null) {
return true;
}
left = head;
return judge(head);
}
public boolean judge(ListNode root) {
if (root == null) {
return true;
}
boolean res = judge(root.next);
res = res && (left.val == root.val);
left = left.next;
return res;
}
}
如果把空间复杂度改为O(1),则会非常复杂。