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

猜你喜欢

转载自blog.csdn.net/a1053904672/article/details/82892653
今日推荐