# 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: ListNode) -> bool:
nums = []
p = head
while p:
nums.append(p.val)
p = p.next
n = len(nums)
for i in range(n//2):
if nums[i] != nums[n - i - 1]:
return False
return True
方法二:空间复杂度O(1)
# 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: ListNode) -> bool:
# 空间复杂度为O(1)解法:
# 1.用快慢指针找到中间位置,
# 2.将后半部分翻转链表(若为奇数个结点,则将中间结点算为前半部分)
# 3.双指针p1,p2,遍历
if not head or not head.next:
return True
# 1.用快慢指针找到中间位置
slow, fast = head, head
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
# 2.迭代翻转后半部分链表,若为奇数个结点,则将中间结点算为前半部分
pre = slow.next
cur = pre.next
pre.next = None
while cur:
tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
p1 = head # 3.双指针p1,p2,遍历
p2 = pre
while p1 and p2:
if p1.val != p2.val:
return False
p1 = p1.next
p2 = p2.next
return True
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)