gpt4 book ai didi

data-structures - Python中的排序链表

转载 作者:行者123 更新时间:2023-12-04 07:07:47 25 4
gpt4 key购买 nike

我在弄清楚如何在 Python 中对单链表进行排序时遇到了一些麻烦。我已经想出了如何创建一个链表并将数据推送到它上面,但是我如何以排序的格式推送它(在所有数据推送到它之后不排序)或者只是以任何方式对其进行排序?

客观的

根据用户输入创建一个排序的数字单链表。
程序逻辑:
要求一个数字,将该数字添加到列表中的排序位置,打印列表。
重复直到他们为数字输入 -1。

当前代码

#!/usr/bin/env python

class node:
def __init__(self):
self.data = None # contains the data
self.next = None # contains the reference to the next node


class linked_list:
def __init__(self):
self.cur_node = None

def add_node(self, data):
new_node = node() # create a new node
new_node.data = data
new_node.next = self.cur_node # link the new node to the 'previous' node.
self.cur_node = new_node # set the current node to the new one.

def list_print(self):
node = self.cur_node # cant point to ll!
while node:
print(node.data)
node = node.next


def main():
ll = linked_list()

num=int(input("Enter a num to push onto the list, -1 to stop: "))
while num!=-1:
data=num
ll.add_node(data)
num=int(input("Enter a num to push onto the list, -1 to stop: "))

print("\n")
ll.list_print()
main()

我真的被困在这里了。预先感谢您的任何帮助!

最佳答案

这应该这样做:

class Node:
def __init__(self):
self.data = None
self.next = None

class LinkedList:
def __init__(self):
self.head = None

def addNode(self, data):
curr = self.head
if curr is None:
n = Node()
n.data = data
self.head = n
return

if curr.data > data:
n = Node()
n.data = data
n.next = curr
self.head = n
return

while curr.next is not None:
if curr.next.data > data:
break
curr = curr.next
n = Node()
n.data = data
n.next = curr.next
curr.next = n
return

def __str__(self):
data = []
curr = self.head
while curr is not None:
data.append(curr.data)
curr = curr.next
return "[%s]" %(', '.join(str(i) for i in data))

def __repr__(self):
return self.__str__()

def main():
ll = LinkedList()
num = int(input("Enter a number: "))
while num != -1:
ll.addNode(num)
num = int(input("Enter a number: "))
c = ll.head
while c is not None:
print(c.data)
c = c.next


>>> main()
Enter a number: 5
Enter a number: 3
Enter a number: 2
Enter a number: 4
Enter a number: 1
Enter a number: -1
1
2
3
4
5

关于data-structures - Python中的排序链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19217647/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com