python中单链表

#对于在第一个位置插入或者删除需要特殊处理
class Node():
    def __init__(self,data=None,pnext=None):
        self.data=data
        self.next=pnext

    def __repr__(self):#返回一个可以用来表示对象的可打印字符串
        return str(self.data)

#单链表的实现
class Chain():
    def __init__(self):
        self._head=None
        self.length=0

    #判断是否为空
    def isEmpty(self):
        return self.length==0

    #链表尾部插入数据
    def append(self,data):
        node=Node(data)
        if self._head==None:
            self._head=node
        else:
            be_node=self._head
            while be_node.next:
                be_node=be_node.next
            be_node.next=node
        self.length+=1

    #插入数据
    def insert(self,index,data):
        if self.isEmpty():
            return
        if index<=0 or index>=self.length:
            print('超出下标限制')
            return
        in_node=Node(data)
        node=self._head
        count=0
        if index==1:
            in_node.next=node
            self._head=in_node
            self.length += 1
            return
        else:
            while True:
                count+=1
                if count==index-1:
                    in_node.next=node.next
                    node.next=in_node
                    self.length+=1
                    return
                node = node.next

    #删除数据
    def delete(self,index):
        if self.isEmpty():
            return
        if index<=0 or index>=self.length:
            print('超出下标限制')
            return
        node = self._head
        if index==1:
            self._head=node.next
        else:
            count=1
            while True:
                if count==index-1:
                    node.next=node.next.next
                    break
                count+=1
                node = node.next
            self.length-=1

    #打印数据
    def __repr__(self):
        if self.isEmpty():
            print('链表是空的')
            return
        nlist=''
        node=self._head
        while node:
            nlist+=node.data+' '
            node=node.next
        return nlist

if __name__=='__main__':
    chain=Chain()
    chain.append('A')
    chain.append('e')
    chain.append('B')
    chain.append('C')
    chain.append('D')
    chain.insert(1,'z')
    print(chain)
    chain.insert(2, 'v')
    print(chain)
    chain.delete(1)
    print(chain)
    chain.delete(2)
    print(chain,chain._head,chain.length)
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值