2020-12-24

python单链表具体代码及其实现

这是我12.24号的成果,如果对代码有好的建议,在这里提前谢谢您,如果你是新手有不理解的,在下方评论,看到第一时间会帮你解答

is_empty() 链表是否为空
length() 链表长度
travel() 遍历整个链表
add(item) 链表头部添加元素
append(item) 链表尾部添加元素
insert(pos, item) 指定位置添加元素
remove(item) 删除节点
search(item) 查找节点是否存在

class Node(object):
def init(self,item):
self.item=item
self.next=None

class SingleLinkList(object):
def init(self):
self.head=None

def is_empty(self):
    return self.head==None

def length(self):
    count=0
    cur=self.head
    while cur!=None:
        count=count+1
        cur=cur.next
    return count

def travel(self):
    cur=self.head
    while cur!=None:
        print(cur.item,end=" ")
        cur=cur.next
    print("")

def append(self,item):
    node=Node(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=Node(item)
    node.next=self.head
    self.head=node
    

def insert(self,pos,item):
    if pos>(self.length()-1):
        self.append(item)
    elif pos<=0:
        self.add(item)
    else:
        node=Node(item)
        count=0
        pre=self.head
        while count<(pos-1):
            count+=1
            pre=pre.next
        node.next=pre.next
        pre.next=node
        
        
def remove(self,item):
    cur=self.head
    pre=None
    while cur!=None:
        if cur.item==item:
            if cur==self.head:
                self.head=cur.next
            else:
                pre.next=cur.next
            break
        else:
            pre=cur
            cur=cur.next
                
            
            
    

def search(self,item):
    cur=self.head
    while cur!=None:
        if cur.item==item:
            return True
        cur=cur.next
    return False

if name==“main”:
SLink=SingleLinkList()
print(SLink.is_empty())
print(SLink.length())
SLink.append(1000)
SLink.append(1700)
SLink.insert(2,500)
SLink.add(200)
SLink.add(300)
SLink.insert(3,400)
print(SLink.is_empty())
print(SLink.length())
SLink.travel()
SLink.remove(500)
SLink.travel()

如果您在成功前停止下脚步,你之前为成功打下的铺垫将全为零。
一起加油,铁铁!!!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值