【问题标题】:Insert new value Into SortedLinked List using Python?使用Python将新值插入SortedLinked List?
【发布时间】:2019-12-13 13:55:28
【问题描述】:

我实现了以下代码,它可以工作,但它在链表末尾添加了新值,例如 [1,2,3,6],值 4 结果是 [1,2,3,6,4] 这是错误的 正确的结果是[1,2,3,4,6]

# Singly-linked lists are already defined with this interface:
class ListNode(object):
    def __init__(self, x):
        self.value = x
        self.next = None

def insertValueIntoSortedLinkedList(head, valuetoInsert):

    currentNode = head

    while currentNode is not None:
        if currentNode.next is None:
            currentNode.next = ListNode(valuetoInsert)
            return head
        currentNode = currentNode.next

我的问题如何修改 insertValueIntoSortedLinkedList 函数 谢谢

【问题讨论】:

    标签: python-3.x linked-list


    【解决方案1】:

    我对@9​​87654321@ 做了一些更改。基本上,错误是您不比较要插入的值是否小于当前值(因此您总是将新值插入到结尾)。

    # Singly-linked lists are already defined with this interface:
    class ListNode(object):
        def __init__(self, x):
            self.value = x
            self.next = None
    
    def insertValueIntoSortedLinkedList(head, valuetoInsert):
        currentNode = head
        while True:
            # is current value greater than value we are going to insert?
            if currentNode.value > valuetoInsert:
                # yes, create new node with old value
                next_node = ListNode(currentNode.value)
                next_node.next = currentNode.next
    
                # replace current value with new value (which is lower than old value)
                currentNode.value = valuetoInsert
    
                # set next node to new node we created previously (with old value)
                currentNode.next = next_node
                # we are done, return
                return
    
            # we are at the end, so break from while-loop
            if currentNode.next is None:
                break
    
            currentNode = currentNode.next
    
        # the valuetoInsert is greater than all values so far, so insert it to the end
        currentNode.next = ListNode(valuetoInsert)
    
    def print_list(head):
        """ Helper method to print the list """
        currentNode = head
    
        while currentNode is not None:
            print(currentNode.value)
            currentNode = currentNode.next
    
    l = ListNode(1)
    insertValueIntoSortedLinkedList(l, 2)
    insertValueIntoSortedLinkedList(l, 3)
    insertValueIntoSortedLinkedList(l, 6)
    
    insertValueIntoSortedLinkedList(l, 4)  # this inserts value before 6
    
    print_list(l)
    

    打印:

    1
    2
    3
    4
    6
    

    【讨论】:

    • 谢谢安德烈·凯塞利
    猜你喜欢
    • 2018-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-08
    • 2011-11-01
    • 2015-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多