简体   繁体   English

如何将节点添加到链表?

[英]How to add a node to a linked list?

I'm creating a function that takes in a sorted linked list and a value.我正在创建一个 function ,它接受一个排序的链表和一个值。 I create a new node with the given value by new_node = LN(v).我用 new_node = LN(v) 的给定值创建了一个新节点。 I am trying to return a linked list with the new node in the correct position.我正在尝试在正确的 position 中返回带有新节点的链表。 The example will help clarify.该示例将有助于澄清。

Ex)前任)

ll = converts_list_to_linked_list([4, 7, 9, 14]) #I have a linked list: 4->7->9->12->14 ll = converts_list_to_linked_list([4, 7, 9, 14]) #我有一个链表:4->7->9->12->14

The Function: Function:

insert_ordered(ll, 12) insert_ordered(ll, 12)

returns a linked list of "4->7->9->12->14->None"返回“4->7->9->12->14->None”的链表

I am completely stuck on how to insert the new node in the correct position.我完全不知道如何在正确的 position 中插入新节点。 The last else statement in my function is incorrect.我的 function 中的最后一条 else 语句不正确。

def insert_ordered(ll,x):
    new_node = LN(v) #Creates new node

    #If given ll is empty, newnode is the linkedlist
    if  ll == None:
        ll = new_node

    #Makes new_node the head of ll if first val is >= new_node value.
    elif ll.value >= new_node.value:
        temp = ll
        ll = new_node
        ll.next = temp

    #[ERROR] Adds new_node between two nodes of ll in sorted order. 
    else:
        while ll.next != None:
            if ll.value < new_node.value:
                ll = ll.next
                new_node.next = ll.next
                ll.next = new_node

    return ll

After solving this iteratively, is it possible to solve it recursively?迭代解决后,是否可以递归解决?

Try this:尝试这个:

class LN:
    def __init__(self, value):
        self.value = value
        self.next = None

def insert_ordered(root, data):
    node = LN(data)
    if root == None:
        return node
    else:
        if root.value > data:
            node.next = root
            return node
        else:
            temp, prev = root, None
            while temp.next and temp.value <= data:
                prev = temp
                temp = temp.next

            if temp.next == None and temp.value <= data:
                temp.next = node
            else:
                node.next = prev.next
                prev.next = node

            return root

root = None
root = insert_ordered(root, 4)
root = insert_ordered(root, 7)
root = insert_ordered(root, 9)
root = insert_ordered(root, 14)
root = insert_ordered(root, 12)
#4->7->9->12->14

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM