请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
O(n) time and O(n) space
class Solution:
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
stack = []
while head != None:
stack.append(head.val)
head = head.next
return stack == stack[::-1]
O(n) time and O(1) space 快慢指针,找到中点,翻转后半段,然后两个半个链表判断是否回文
class Solution:
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if not head or not head.next:
return True
slow = fast = head
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
slow = slow.next
slow = self.reverseList(slow)
while slow:
if head.val != slow.val:
return False
slow = slow.next
head = head.next
return True
def reverseList(self, head):
new_head = None
while head:
p = head
head = head.next
p.next = new_head
new_head = p
return new_head