python使用链表实现列表list

在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

 

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python链表列表是两种不同的数据结构。 列表List)是Python中最用的数据类型之一。它是一种有序、可变的集合,可以包含任意类型的元素。列表使用方括号 [] 来表示,元素之间使用逗号分隔。列表支持索引和切片操作,可以进行增删改查等操作。 链表(Linked List)是一种数据结构,由一系列节点组成,每个节点包含一个数据元素和一个指向下一个节点的指针。不同于列表链表的内存分配不是连续的,而是通过指针将节点连接起来。链表的优点是插入和删除操作比较高效,但是访问某个特定位置的元素需要遍历整个链表,效率较低。 在Python中,没有内置的链表类型。但可以通过类和对象的方式来实现链表。例如,可以定义一个Node类表示链表的节点,然后使用这个类创建节点对象并通过指针连接它们。 以下是一个简单的链表示例: ```python class Node: def __init__(self, data): self.data = data self.next = None # 创建链表 node1 = Node(1) node2 = Node(2) node3 = Node(3) node1.next = node2 node2.next = node3 # 遍历链表 current = node1 while current: print(current.data) current = current.next ``` 这是一个包含3个节点的链表,节点的数据分别为1、2和3。通过 `next` 指针将它们连接起来,并使用循环遍历链表并输出节点的数据。 需要注意的是,Python列表操作更加灵活和方便,而链表则适合于频繁进行插入和删除操作的场景。根据实际需求选择合适的数据结构。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值