带头节点版本的单链表(Python实现)

###打卡,带头节点版本的单链表(Python实现)
Day 13 :访问链表第i个节点
依然考虑到新接触链表的朋友不习惯使用它,本次作业还是强化下链表的基本操作。

class Node:
    def __init__(self,x=None):
        self.value=x
        self.next=None
        
class SingleLinkedList:
    #带头节点版本的单链表
    def __init__(self):
        self.head=Node()
    
    def is_empty(self):
        #判空
        return self.head.next==None

    def size(self):
        #长度
        #指向头节点下一个,即第一个节点
        cur=self.head.next
        count=0
        while cur!=None:
            count+=1
            cur=cur.next
        return count
    
    def print_all(self):
        #打印
        cur=self.head.next
        while cur!=None:
            print(cur.value)
            cur=cur.next
            print(' ')
    
    def add(self,value):
        #头插
        node=Node(value)
        node.next=self.head.next
        self.head.next=node

    def append(self,value):
        #尾插
        if self.is_empty():
            self.add(value)
        else:
            node=Node(value)
            cur=self.head
            while cur.next!=None:
                cur=cur.next
            cur.next=node
    
    def insert(self,pos,value):
    #   指定位置插入
        if pos<=0:
            self.add(value)#调用头插
        elif pos>self.size()-1:
            self.append(value)#调用尾插
        else:
            node=Node(value)
            count=0
            cur=self.head
            while count<pos-1:
                cur=cur.next
                count+=1
            node.next=cur.next
            cur.next=node
    
    def get_index(self,index):
        #获取index下标位置元素
        if  self.size()>index>=0:
            cur=self.head.next
            pos=0
            while pos<index:
                cur=cur.next
                pos+=1
            return cur.value
        else:
            return 'index_error' 
    
    def delet_index(self,index):
        #删除index下标位置元素
        if  self.size()>index>=0:
            cur=self.head.next
            pos=0
            while pos<index-1:
                cur=cur.next
                pos+=1
            cur.next=cur.next.next
        else:
            return 'index_error' 

if __name__ == "__main__":
    li = SingleLinkedList()
    li.add(3)
    li.add(2)
    li.add(1)
    li.append(4)
    print(li.get_index(3))
    li.delet_index(1)
    li.print_all()

    
        
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值