【发布时间】:2015-02-11 20:41:03
【问题描述】:
我在为有序链表创建插入函数时遇到问题。这是我目前所拥有的:
class Node:
def __init__(self, initial_data):
self.data = initial_data
self.next = None
def get_data(self):
return self.data
def get_next(self):
return self.next
def set_data(self, new_data):
self.data = new_data
def set_next(self, new_next):
self.next = new_next
class LinkedList:
def __init__(self):
self.head = None
def __str__(self):
output_string = ''
current = self.head
while current is not None:
output_string += str(current.get_data())
next_node = current.get_next()
if next_node is not None:
output_string += "->"
current = next_node
return output_string
def insert(self, data):
other = self.head
previous = None
if other is None:
new_node = Node(data)
new_node.set_next(self.head)
self.head = new_node
else:
while data > other.get_data():
previous = other
other = other.get_next
previous.set_next(Node(data))
【问题讨论】:
-
这看起来工作量很大!我建议改用内置的
list类型。 -
@Kevin:
list不是链表,尤其不是用于数据结构类的目的.. -
那么你卡在哪里了?你实现了something,你能给我们一些示例输入、预期输出以及你得到的结果吗?如果有错误,请也包括那些(完整的追溯)。
-
顺便说一句:没有充分的理由在 Python 中使用 getter 和 setter。只需使用该属性,如果您发现需要自定义逻辑来获取或设置,请使用
@property
标签: python python-3.x