【发布时间】:2021-03-04 17:46:56
【问题描述】:
我是 python 新手。我有以下存储在链接列表中的书籍列表,我想使用快速排序对它们进行排序,但不幸的是,我遇到了一个问题。
class Node:
def __init__(self, data=None):
self.data = data
self.prev = None
self.next = None
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def append_value(self, x):
if not isinstance(x, Node):
x = Node(x)
if self.is_empty():
self.head = x
else:
current = self.head
while current.next:
current = current.next
current.next = x
x.prev = current
self.tail = x
def length(self):
count = 0
current = self.head
while current:
count += 1
current = current.next
return count
def is_empty(self):
return self.head is None
def __str__(self):
to_print = ''
current = self.head
while current:
to_print += f'{current.data} <-> '
current = current.next
if to_print:
return f'[{to_print[:-5]}]'
return '[]'
def quick_sort(self, arr):
if self.length() < 2:
return self
else:
pivot = self.tail.data
smaller, equal, larger = [], [], []
current = self.head
while current:
if current.data < pivot:
smaller.append(current.data)
elif current.data == pivot:
equal.append(current.data)
else:
larger.append(current.data)
current = current.next
return self.quick_sort(smaller) + equal + self.quick_sort(larger)
这是快速排序方法,但它在“返回 self.quick_sort(smaller) + equal + self.quick_sort(larger)”上给了我 RecursionError。如何使用快速排序对链表进行排序?
my_list = DoublyLinkedList()
my_list.append_value('In Search of Lost Time')
my_list.append_value('Ulysses by James Joyce')
my_list.append_value('Within a Budding Grove')
my_list.append_value('The Guermantes Way')
my_list.append_value('In Search of Lost Time')
my_list.append_value('Sodom & Gomorrah')
my_list.append_value('One Hundred Years of Solitude')
my_list.append_value('War and Peace')
print(f'List of Books: {my_list}')
print(f'Quick Sort: {my_list.quick_sort(my_list)}')
【问题讨论】:
-
第 1 步是使用 GUI 调试器调试您的程序,并逐行逐行查看代码的执行与您的预期不同的地方。听起来您还没有以这种方式调试过。
-
我尝试调试代码。但这并没有解决问题。
-
当我这样做时,问题就在这里:更小,相等,更大 = [],[],[] 链表不接受
。我想我必须将其转换为 main.Node'>,但我无法这样做(尝试调试无法解决问题)。谢谢。 -
旁注:将链表中的值复制到标准列表中感觉有点像作弊:每个值都会在某个时候附加到列表中。如果这样做,您可能想知道为什么不将链接列表完全复制到列表中,对该列表进行排序,然后从中创建链接列表。如果这是一项作业,那么我无法想象应该使用标准列表。
标签: python linked-list quicksort