[英]How to reverse a linked list while keeping the original linked list unchanged
如何反转链表保持原始不变? 如果我正在反转链接列表,它也会更改原始链接列表。
class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
p = head
q = self.reverse_list(head)
while p and q:
if p.val != q.val:
return False
else:
p = p.next
q= q.next
return True
def reverse_list(self, head):
curr = head
prev = None
while curr is not None:
tmp = curr.next
curr.next = prev
prev = curr
curr = tmp
return prev
您可以使用递归制作一个非常美观(但在 python 中不是超级有效的解决方案)。 基本上,您可以切换递归顺序,给您一个正向生成器和一个反向生成器,然后是 zip 并进行比较
class Solution:
def isPalindrome(self, head):
return all(a.val == b.val
for a,b
in zip(self.forward(head), self.backward(head)))
def forward(self, head):
if head is None:
return
yield head
yield from self.forward(head.next)
def backward(self, head):
if head is None:
return
yield from self.backward(head.next)
yield head
这很有吸引力,但由于递归限制,不太可能处理非常大的列表。
对于更大的输入,您可以制作forward()
生成器的非递归版本并从中呈现列表。 然后将列表与其相反的列表进行比较:
class Solution:
def isPalindrome(self, head):
v = list(self.forward(head))
return v == v[::-1]
def forward(self, head):
while head:
yield head.val
head = head.next
这使用 O(n) 空间,但应该表现得相当好。
另一种解决方案是遍历列表,添加parent
属性为 go。 最后,您将拥有列表的尾部,并且可以并行跟随父引用再次从头部运行列表并进行比较。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.