Python数据结构与算法03-节点与单链表

复制代码
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class SingleLinkList:
    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

    def add(self,item):
        '''在链表头部添加元素'''
        node=ListNode(item)
        node.next=self.__head
        self.__head=node
    def insert(self,pos,item):
        '''在指定位置添加元素
        :param pos 索引从0开始
        '''
        if pos<0:
            self.add(item)
        elif pos>=self.length():
            self.append(item)
        else:
            node=ListNode(item)
            pre=self.__head
            count=0
            while count<pos-1:
                pre=pre.next
                count+=1
            node.next=pre.next
            pre.next=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):
        '''删除制定元素病返回删除前元素的索引'''
        print(self.search(item))
        cur=self.__head
        pre=None
        while cur!=None:
            if cur.val==item:
                if pre==None:
                    self.__head=cur.next
                else:
                    pre.next=cur.next
                    cur.next=None

                break
            else:
                pre=cur
                cur=cur.next
复制代码

 

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