【问题标题】:Insert in Ordered Linked List (Python) [closed]插入有序链表(Python)[关闭]
【发布时间】: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


【解决方案1】:

您需要将您的项目插入到列表中。这意味着您需要:

  • 在你要插入的地方打断链条
  • 创建一个新节点
  • 再次加入链,新节点位于中间。

从技术上讲,您不需要断开链,因为在 previous 项目上设置下一个链接会清除旧链接,所以您需要做的仍然是再次加入链:

while data > other.get_data():
    previous = other
    other = other.get_next()
new = Node(data)
previous.set_next(new)
new.set_next(other)

我还纠正了一个不同的错误,你没有调用Node.get_next()

接下来,您需要更多地考虑边缘情况。当您到达链的end,但没有找到node.get_data() 大于插入数据的任何 节点时会发生什么?

您需要调整 while 循环以确保您针对这种情况进行测试;对于链的最后一个元素,other 将是 None

while other is not None and data > other.get_data():
    previous = other
    other = other.get_next()
new = Node(data)
previous.set_next(new)
new.set_next(other)

您还可以采取其他措施来改进您的代码。在 Python 中不需要使用 setter 和 getter;以后将属性转为@propertys 不涉及任何成本,所以在这里使用属性即可。

您还可以让您的 Node() 在构造函数中接受下一个元素,这样可以更轻松地插入元素。

您可以使用str.join() 在序列元素之间插入固定字符串。将所有 data 属性放入 Python list 并加入该列表。

创建初始元素时不需要将self.head设置为下一个节点(当self.headNone时);无论如何,这已经是默认值了:

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

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

    def __str__(self):
        data_list = []    
        current = self.head
        while current is not None:
            data_list.append(str(current.data))
            current = current.next
        return '->'.join(data_list)

    def insert(self, data):
        other = self.head
        previous = None
        if other is None:
            self.head = Node(data)
        else:
            while other is not None and data > other.data:
                previous = other
                other = other.next
            previous.next = Node(data, other)

演示:

>>> ll = LinkedList()
>>> str(ll)
''
>>> ll.insert(10)
>>> str(ll)
'10'
>>> ll.insert(20)
>>> str(ll)
'10->20'
>>> ll.insert(15)
>>> str(ll)
'10->15->20'

【讨论】:

    【解决方案2】:

    我想改变这个:

        else:
                while data > other.get_data():
                    previous = other
                    other = other.get_next
                previous.set_next(Node(data))
    

    对此,应该让它工作。

        else:
                # First condition will short circuit so there won't be exception on calling other.get_data() if other is None
                while other is not None and data > other.get_data():
                    previous = other
                    other = other.get_next()
                node = Node(data)
                node.set_next = previous.get_next()
                previous.set_next(node)
    

    另外,getter 和 setter 方法在 python 中并不是必需的。 如果您需要这种行为,约定是使用 @property 注释,私有成员通常以 _ 为前缀。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-17
      • 1970-01-01
      • 2020-06-28
      • 1970-01-01
      相关资源
      最近更新 更多