后浪云Python教程:python创建链表的两种形式

后浪云Python教程:python创建链表的两种形式插图

说明

1、头插法将结点插入头结点后面,新加入的结点next指向原来head指向的结点。

head改为新的结点。

2、尾插法将结点插入尾点前,新节点的next指向tail,tail更新为新节点。

实例

class Node:
    def __init__(self,item):
        self.item = item
        self.next = None
 
class HandleNode:
    def create_linklist_head(self,li):
        head = Node(li[0])
        for element in li[1:]:
            node = Node(element)
            node.next = head
            head = node
        return head
 
    def create_linklist_tail(self,li):
        head = Node(li[0])
        tail = head
        for element in li[1:]:
            node = Node(element)
            tail.next = node
            tail = node
        return head
 
    def print_linklist(self,head):
        while head:
            print(head.item,end=',')
            head=head.next

以上就是python创建链表的两种形式,希望对大家有所帮助。更多Python学习指路:后浪云python教程

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

THE END