在python中插入链表的头

2024-10-05 14:30:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个函数,它接受一个链表的头和一个值,用这个值创建一个节点,set节点.下一个,然后将新节点更新为head。我让它发挥了作用,但我觉得我通过返回值来做这件事效率很低,所以我想知道是否有更优雅的方法来实现这一点。在

下面是我使用的代码:

#!/usr/bin/env python3
"""
This module is a linked list implementation.
"""

class Node:
    """
    Node structure to be used in our linked list.
    """
    def __init__(self, value):
        self.value = value
        self.next = None

def linked_insert(head, value):
    """
    Insert new node to the tail of the linked list.
    Time Complexity: O(n)
    """
    current = head
    while current.next is not None:
        current = current.next
    current.next = Node(value)

def linked_insert2(head, value):
    """
    Insert new node to the head of the linked list, making sure to update head.
    Time Complexity: O(1)
    """
    to_insert = Node(value)
    to_insert.next = head
    head = to_insert
    return head


def linked_extract(head):
    """
    Extract the last element in the linked list
    """
    current = head

    while current.next.next is not None:
        current = current.next

    tail = current.next
    current.next = None

    return tail


def linked_display(head):
    """
    Print all node values in the linked list
    """
    current = head
    while current is not None:
        print(current.value)
        current = current.next


# Test Program
head = Node(5)
# linked_insert(head, 1)
# linked_insert(head, 2)
# linked_insert(head, 3)
#
# print(linked_extract(head).value)

head = linked_insert2(head, 1)
head = linked_insert2(head, 2)
head = linked_insert2(head, 3)
linked_display(head)

有没有一种方法可以做到这一点,而不必在测试程序中返回head的值并设置head=返回值?在

有问题的函数是linked_insert2()。整个程序是python中的一个链表实现。在

使用链表类实现:

^{pr2}$

Tags: thetononenodeisvaluedefcurrent