【问题标题】:How do implement sorting to this linkedlist?如何实现对这个链表的排序?
【发布时间】:2019-11-05 07:06:49
【问题描述】:

所以我需要将数据从低到高排序。所以最低值的指针将指向下一个最高值,依此类推。到目前为止,它只指向下一个插入的数据,而不管数据如何。

我需要在附加每个值时对其进行排序

代码:

    def AppendNode(self, node):
    if self._isleagl(node):                         #just a error checking method
        if self.list_start == None:                 #checks if list is empty
            self.list_start = node      
            node._set_pointer(None) 
        else:                                       #list not empty
            item = self.list_start
            while item:
                if item == node:                    #Checks for duplicates
                    print("This is not allowed")
                elif item._get_pointer() is None:   #If it is end of the List
                    item._set_pointer(node)
                    node._set_pointer(None)
                    break
                else:                              #incrimets to the next node via pointer
                    item = item._get_pointer()

当前输出:

 Index   Data   Pointer
   0      1       1
   1      6       2
   2      3       3
   3      7      None

期望的输出:

 Index   Data   Pointer
   0      1       2
   1      6       3
   2      3       1
   3      7      None

编辑:

所以我暗示了这一点,但是它仍然不起作用。我认为这与 elif 语句本身有关。

                elif item.data < node.data:
                    node._set_pointer(item._get_pointer())
                    item = item._get_pointer()
                    break
                elif item.data > node.data:
                    item._set_pointer(node)
                    item._get_pointer()
                    break

【问题讨论】:

    标签: python sorting oop linked-list


    【解决方案1】:

    如果您想按排序顺序维护列表,则有时需要在中间插入节点,而不是总是将它们放在末尾:

    # insert node after item
    node.set_pointer(item.get_pointer())  # whatever followed item now follows node
    item.set_pointer(node)                # node now follows item
    

    【讨论】:

    • 我该怎么做呢?我是否需要更多的 elif 语句来查看数据是 > 还是
    • 当您遍历列表时,查看itemitem.get_pointer() 以查看node 是否位于它们之间。如果node 属于item.get_pointer() 之后,请继续向下迭代。查看您在问题中更新的代码,我认为您的情况大部分是正确的,但您实际上并没有按照我在回答中建议的操作来确保正确插入节点。
    • 对不起,我真的不明白您在回答中给出的建议以及如何实施它。您能否举例说明其中一个 elif 语句应该包含什么内容?编辑:对不起,我没有看到你的其他答案
    【解决方案2】:

    从头开始编写它比尝试修复代码片段更简单——希望一个简单的演示在实践中展示了整个概念,有助于让您的代码走上正轨。 :)

    from typing import Optional
    
    class SortedList:
        """A list of ints that keeps itself in sorted order on insert."""
        def __init__(self, data: int):
           self.data = data
           self.next: Optional['SortedList'] = None
    
        def insert(self, data: int) -> 'SortedList':
            """Insert a new node into this list, and return the first node of the list."""
            node = SortedList(data)
            if node.data < self.data:
                # node is now at the head of the list
                node.next = self
                return node
            # Find the list node that will precede the new node.
            prev = self
            while prev.next is not None and prev.next.data < node.data:
                prev = prev.next
            # Insert the new node after prev.
            node.next = prev.next
            prev.next = node
            # Self remains the first node of the list.
            return self
    
        def print(self) -> None:
            """Print the list starting at this node."""
            print(self.data)
            if self.next:
                self.next.print()
    
    sorted_list = SortedList(9)
    sorted_list = sorted_list.insert(6)
    sorted_list = sorted_list.insert(1)
    sorted_list = sorted_list.insert(3)
    sorted_list = sorted_list.insert(7)
    sorted_list.print()
    # output:
    #  1
    #  3
    #  6
    #  7
    #  9
    

    【讨论】:

    • 这很好,还有一个问题:应该可以通过这种方式实现删除吗?
    • 是的,当然。您所要做的就是重新排列“下一个”指针,以便它们跳过您要删除的项目。
    猜你喜欢
    • 2014-01-22
    • 1970-01-01
    • 2021-07-30
    • 2014-02-20
    • 1970-01-01
    • 2013-04-08
    • 2019-07-29
    • 1970-01-01
    相关资源
    最近更新 更多