中断了好多次 😭
再次捡起来,周一,坚持走下去
https://leetcode-cn.com/problems/valid-palindrome/description/
一个链表是否回文?
不能开额外的空间,时间复杂度O(n) 嗯,其实是有一个“巧妙”的方法,常规解法,不用Python的语法糖
就是先利用快慢指针的方法,找到中间节点,然后从中间节点开始,将链表逆置,然后再分别从头节点和逆置后的节点依次进行比较就好了
这道题还是综合考察了链表的基本操作,脑子要稍微“清楚”一些,难度并不大,但一次写对,也不是那么容易
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
# find mid node
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
node = None
# reverse list
while slow:
nxt = slow.next
slow.next = node
node = slow
slow = nxt
while node:
if node.val != head.val:
return False
else:
node = node.next
head = head.next
return True
网友评论