【发布时间】:2021-05-24 07:04:58
【问题描述】:
def is_palindromic_linked_list(head):
if head is None or head.next is None:
return True
slow = head
fast = head
while fast is not None and fast.next is not None:
fast = fast.next.next
slow = slow.next
head_second_half = reverse(slow) #6, 4, 2 => 2, 4, 6
copy_head_second_half = head_second_half #<------HERE: copied linkedlist
while (head is not None and head_second_half is not None):
if head.value != head_second_half.value:
break
head = head.next
head_second_half = head_second_half.next
reverse(copy_head_second_half) #<---HERE: reversed the copied version of the linkedlist to set it back to how it was.
if head is None or head_second_half is None:
return True
return False
def reverse(head):
prev = None
while (head is not None):
next = head.next
head.next = prev
prev = head
head = next
return prev
这有什么意义?链表的工作方式是否与变量不同,因为更改复制版本会更改原始版本?
【问题讨论】:
-
在大多数情况下,分配不会创建副本。
-
链表没有被复制,只是对链表的引用。只有 1 个链表,但有 2 个变量指向它。
标签: python python-3.x linked-list palindrome