我关于排序链表实现的逻辑是错误的吗



我一直在练习在Python中实现排序(操作期间自动更新(链表(通常人们使用C++来实现(。

目前,我已经完成了以下代码(在文件definitions.py中(:

class LinkedListException(Exception):
pass

class Node:
def __init__(self, content=None):
self.content = content
self.adjacent = None

class SortedLinkedList:
def __init__(self):
self.head = None
self.size = 0
def size(self):
return self.size
def retrieve(self, entry):
tmp = self.head
while tmp is not None:
if tmp.content == entry:
return tmp
tmp = tmp.adjacent
raise LinkedListException(f"Entry {entry} not found.")
def append(self, entry):
if self.head is None:
self.head = Node(entry)
return
tmp = self.head
while tmp.adjacent is not None:
if tmp.content > entry:
print("p", tmp.content)
break
tmp = tmp.adjacent
n = Node(entry)
tmp.adjacent = n
n.adjacent = None

在main.py中:

from sortedLinkedLists.definitions import SortedLinkedList

def main():
obj = SortedLinkedList()
obj.append(1)
obj.append(3)
obj.append(2)
print(obj.head.content)
print(obj.head.adjacent.content)
print(obj.head.adjacent.adjacent.content)

if __name__ == '__main__':
main()

(第1行的描述:我使用了pycharm,我的项目名称是sortedLinkedLists(

但我刚刚得到:

1
3
2

按照我所附的原始顺序。

我希望在插入过程中自动对列表进行排序,所以一定有问题。

有人能帮我吗?

附言:我尝试了其他测试用例,它只是按顺序附加了所有测试用例,而没有对它们进行实际排序。目前,这与链表完全相同!

您在append:中的逻辑有问题

给你:

def append(self, entry):
n=Node(entry)
if self.head is None:
self.head = n
return
if self.head.content > entry:
self.head, n.adjacent = n, self.head
return

tmp=self.head
while tmp.adjacent and tmp.adjacent.content < entry:
tmp=tmp.adjacent
n.adjacent = tmp.adjacent
tmp.adjacent = n

最新更新