19/300
- 回文链表
请判断一个链表是否为回文链表。(注意:空链表也算回文链表)
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
输入: -129->-129
输出: true
关于回文的,大概python里都可以用[::-1]?!算是偷懒了。。
突然想到之前刷的206 反转链表+876 链表的中间结点 ,找到中间节点,然后用中间节点作为脑袋,反转后半串儿,也是可行的:
-11->23->23->-11
23->-11 反转 -11->23
所以对比:
旧:-11->23 ->23 ->None
新:-11->23 ->None
11->23->33->23->11
33->23->11 反转 11->23->33
所以对比:
旧:11->23->33->None
新:11->23->33->None
奇偶完全不碍事。
class Solution:
def isPalindrome_01(self, head: ListNode) -> bool:
lst = []
while head:
lst.append(head.val)
head = head.next
return lst == lst[::-1]
def isPalindrome_02(self, head: ListNode) -> bool:
if not head or not head.next:
return True
fast = slow = head
# mittel:
while fast and fast.next:
fast = fast.next.next
slow = slow.next
new_head = None
# reverse:
while slow:
new_head, new_head.next, slow = slow , new_head ,slow.next
while new_head:
if new_head.val != head.val:
return False
new_head = new_head.next
head = head.next
return True