我正在用Linkcode练习编程技能。 我正在做一个排序列表问题,其中我需要使用恒定的空间复杂度在O(n log n)时间内对链接列表进行排序。我想使用快速排序算法来做到这一点。
我收到错误消息:“追踪(最近一次通话最近):文件“ /code/Main.py”,第20行,在ans = solution.sortList(head)文件“ /code/Solution.py”,第21行,在sortList虚拟中,tail = self.quickSort(head)文件“ /code/Solution.py”,第91行,在quickSort虚拟1中,tail1 = self.quickSort(start)TypeError:'ListNode'对象不可迭代“ 我真的很困惑,因为我没有在第91行中使用任何可迭代的内容。我只是将“ listNode”对象传递给要求“ listNode”输入的递归函数。谁能帮我看看有什么问题吗?
这是我的代码:
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
# quicksorting
class Solution:
"""
@param head: The head of linked list.
@return: You should return the head of the sorted linked list, using constant space complexity.
"""
def sortList(self, head):
# write your code here
if not head:
return None
if head.next is None:
return head
dummy, tail = self.quickSort(head)
return dummy.next
def quickSort(self, start):
dummy = ListNode(0)
dummy.next = start
if not start:
return None
if start.next is None:
return start
slow = start
fast = start.next
while fast:
if fast.next:
fast = fast.next.next
slow = slow.next
else:
break
mid = slow
pivot = mid.val
left = start
leftPrev = dummy
right = mid.next
rightPrev = mid
Tail = mid
while left != mid and right:
while left != mid and left.val < pivot:
left = left.next
leftPrev = leftPrev.next
while right and right.val > pivot:
Tail = Tail.next
right = right.next
rightPrev = rightPrev.next
if left != mid and right:
self.changeNode(left, right, leftPrev, rightPrev)
temp = left
left = right
right = temp
while left != mid:
if left.val <= pivot:
left = left.next
leftPrev = leftPrev.next
else:
nextLeft = left.next
self.insertNode(left, Tail, leftPrev)
Tail = Tail.next
left = nextLeft
while right:
if right.val >= pivot:
right = right.next
rightPrev = rightPrev.next
Tail = Tail.next
else:
nextRight = right.next
self.insertNode(right, dummy, rightPrev)
right = nextRight
midNext = mid.next
mid.next = None
dummy1, tail1 = self.quickSort(start)
dummy2, tail2 = self.quickSort(mid)
dummy.next = dummy1.next
tail1.next = dummy2.next
tail2.next = None
return dummy, Tail
# insert node2 to node1.next of a list
def insertNode(self, node1, node2, prevNode2):
nextNode2 = node2.next
node2.next = node1.next
node1.next = node2
prevNode2.next = nextNode2
# exchange position of node1 and node2 of a list
def changeNode(self, node1, node2, prevNode1, prevNode2):
nextNode2 = node2.next
prevNode1.next = node2
node2.next = node1.next
prevNode2.next = node1
node1.next = nextNode2
答案 0 :(得分:0)
您的quickSort
方法应该返回tuple
(可迭代),就像您在底部使用return dummy, Tail
一样,以便进行多次赋值
dummy1, tail1 = self.quickSort(start)
# return value must be iterable (producing exactly two elements)!
可以工作。在该方法顶部的两个if块中
if not start:
return None # not iterable!
if start.next is None:
return start # not iterable!
但是,您返回None
或start
(两者都是不可迭代的),对于上述分配,它们将因您看到的错误而失败。