Python数据结构与算法03-双链表

双链表

复制代码
class ListNode:
    def __init__(self,val,prev=None,next=None):
        self.val=val
        self.prev=prev
        self.next=next
class DoubleLinkList:
    def __init__(self,node=None):
        self.__head=node
    def is_empty(self):
        '''判断列表是否为空'''
        return self.__head == None

    def length(self):
        '''链表长度'''
        cur = self.__head
        count = 0
        while cur != None:
            count += 1
            cur = cur.next
        return count

    def travel(self):
        '''遍历链表'''
        cur = self.__head
        while cur != None:
            print(cur.val, end=' ')
            cur = cur.next
        print(' ')

    def append(self, item):
        '''在链表尾部添加元素'''
        node=ListNode(item)
        if self.is_empty():
            self.__head=node
        else:
            cur=self.__head
            while cur.next!=None:
                cur=cur.next
            cur.next=node
            node.prev=cur


    def add(self, item):
        '''在链表头部添加元素'''
        node=ListNode(item)
        node.next=self.__head
        self.__head=node
        node.next.prev=node



    def insert(self, pos, item):
        '''在指定位置添加元素
        :param pos 索引从0开始
        '''
        node=ListNode(item)
        if pos<0:
            self.add(node)
        elif pos>(self.length()-1):
            self.append(node)
        else:
            count=1
            cur=self.__head
            while count<=pos:
                cur=cur.next
                count+=1
            node.next=cur
            node.prev=cur.prev
            cur.prev.next=node
            cur.prev=node


    def search(self, item):
        '''查找元素
        若找到元素返回元素索引
        若找不到返回-1
        '''
        cur=self.__head
        count=0
        while cur!=None:
            count+=1
            if cur.val==item:
                return count-1
            else:
                cur=cur.next
        return -1



    def remove(self, item):
        '''删除制定元素病返回删除前元素的索引'''
        cur=self.__head
        while cur.val!=item:
            cur=cur.next
        if cur==self.__head:
            self.__head=cur.next
            if cur.next!=None:#判断链表是否只有一个节点
                cur.next.prev=None
        else:
            cur.prev.next=cur.next
            if cur.next:#判断是否是最后一个节点
                cur.next.prev=cur.prev
复制代码

 

posted @   Junior_bond  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示