链表python实现

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

    def setnext(self, n_next):
        self.next = n_next

class Linklist():
    def __init__(self, head):
        self.head = head
        self.tail = head
        self.ListNode = []
        self.ListValue = []

    def addnode(self, value):#添加
        node = Node(value)
        self.tail.setnext(node)
        self.tail = node

    def getnode(self, node):
        return node.value, node.next

    def traversing(self):  # 遍历
        self.ListNode=[]
        self.ListValue=[]
        value, n_ext = self.getnode(self.head)
        self.ListNode.append(self.head)
        self.ListValue.append(value)
        while (n_ext):
            self.ListNode.append(n_ext)
            value, n_ext = self.getnode(n_ext)
            self.ListValue.append(value)

    def insertnode(self,node1, node2, value):#插入
        node = Node(value)
        node1.setnext(node)
        node.setnext(node2)


data = [1, 2, 3, 4, 5, 7, 8, 9, 10]
head = Node(1)
linkList = Linklist(head)
for i in range(len(data) - 1):
    linkList.addnode(data[i + 1])
linkList.traversing()
print(len(linkList.ListValue))
print(len(linkList.ListNode))
print(linkList.ListValue)
print(linkList.ListNode)
linkList.insertnode(linkList.ListNode[4],linkList.ListNode[5],6)
linkList.traversing()
print(len(linkList.ListValue))
print(len(linkList.ListNode))
print(linkList.ListValue)
print(linkList.ListNode)

输出

9
9
[1, 2, 3, 4, 5, 7, 8, 9, 10]
[<__main__.Node object at 0x00000204AD301BA8>, <__main__.Node object at 0x00000204AD301C18>, <__main__.Node object at 0x00000204AD301C50>, <__main__.Node object at 0x00000204AD301C88>, <__main__.Node object at 0x00000204AD301CC0>, <__main__.Node object at 0x00000204AD301CF8>, <__main__.Node object at 0x00000204AD301D30>, <__main__.Node object at 0x00000204AD301D68>, <__main__.Node object at 0x00000204AD301DA0>]
10
10
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[<__main__.Node object at 0x00000204AD301BA8>, <__main__.Node object at 0x00000204AD301C18>, <__main__.Node object at 0x00000204AD301C50>, <__main__.Node object at 0x00000204AD301C88>, <__main__.Node object at 0x00000204AD301CC0>, <__main__.Node object at 0x00000204AD301DD8>, <__main__.Node object at 0x00000204AD301CF8>, <__main__.Node object at 0x00000204AD301D30>, <__main__.Node object at 0x00000204AD301D68>, <__main__.Node object at 0x00000204AD301DA0>]

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值