python使用链表实现列表list

本文介绍了一种使用Python实现链表的方法,包括节点的定义、基本操作如添加、获取、删除元素,以及清空和获取链表大小等功能。通过具体代码示例,读者可以了解链表数据结构的内部工作原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在python中列表是使用链表实现的,下面使用单向链表实现List

class List():
    class Node():
        def __init__(self,object_,next_node):
            self.object_=object_
            self.next=next_node
    def __init__(self):
        self.__head = List.Node(None, None)
        self.__tail = self.__head
        self.__count=0
        self.__current = self.__head
    def add(self,elment):
        self.__tail.next=List.Node(elment,self.__head)
        self.__tail=self.__tail.next
        self.__count+=1
    def get(self,index):
        if index+1> self.__count:
            raise Exception('index out of range List')
        n=0
        t = self.__head
        while n<index:
            # print(t.object_)
            t=t.next
            n+=1
        return t.object_
    def remove(self,elment):
        n=0
        t=self.__head
        while n<self.__count:
            previous=t
            t=t.next
            next_=t.next
            if (elment is t.object_) or (elment==t.object_):
                previous.next=next_
                self.__count-=1
                return
            n+=1
    def clear(self):
        self.__head = List.Node(None, None)
        self.__tail = self.__head
        self.__count = 0
        self.__current = self.__head
    def size(self):
        return self.__count
    def __len__(self):
        return self.__count
    def insert(self,index,elment):
        t = self.__head
        for i in range(0,self.__count):
            previous = t
            t = t.next
            if i == index:
                previous.next=List.Node(elment,t)
                return True
        return False
    def __next__(self):
        self.__current=self.__current.next
        if self.__current==None:
            return None
        return self.__current

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值