python 单链表

class Node(object):

 def __init__(self,elem):
  self.elem=elem
  self.next=None
   
 
class SingleLineList(object):

 def __init__(self,node=None):
  self.__head=node
   
 def is_empty(self):
  return self.__head==None
   
 def length(self):
  count=0
  cur=self.__head
  while cur!=None:
     count+=1
     cur=cur.next
  return count
   
 def travel(self):
  cur=self.__head
  while cur!=None:
     print(cur.elem, end=" ")
     cur=cur.next
  print("")
 def append(self,item):
  cur=self.__head
  node=Node(item)
  if cur==None:
   self.__head=node
  else:
    while cur.next!=None:
    cur=cur.next
    #node.next=cur
    cur.next=node
     
 def add(self,item):
  cur=self.__head
  node=Node(item)
  if cur==None:
   self.__head=node
  else:
   node.next=cur
   self.__head=node   
    
 def insert(self,pos,item):
  cur=self.__head
  count=0
  #rightp=pos-1
  node=Node(item)
  if pos>(self.length()-1):
   self.append(item)
  elif pos<=0:
   self.add(item)
  elif pos>0 and pos<self.length():
   while count<pos-1:
    count+=1
    cur=cur.next
   node.next=cur.next
   cur.next=node
    
 def remove(self,item):
  cur=self.__head
  cu=self.__head
  count=0
  if cur!=None:
   while cur!=None:
    #count+=1
    if cur.elem==item:
     #print("count=",count)
     break
    else:
     cur=cur.next
     count+=1
  else:
   print("empty")
    
  if count==0:
   self.__head=cu.next.next   
  elif count>=self.length()-1:
   no=0
   while no<count-1:
    cu=cu.next
    no+=1
   cu.next=None
  elif count>0 and count<self.length():
   no=0
   #cur=self.__head
   while no<count-1:
    cu=cu.next
    no+=1
   cu.next=cu.next.next
   #print("no=",no)   
  else:
   print("no such element")
   
 def search(self,item):
   cur=self.__head
   count=0
   if cur!=None:
    while count<self.length():
     if cur.elem==item:
      print(count)
      return
     cur=cur.next
     count+=1
    print("no such element")
   else:
    print("empty") 
 
 
 
 
 
li=SingleLineList()
print(li.is_empty())
print(li.length())

li.append(2)

print(li.is_empty())
print(li.length())

li.append(3)
print(li.is_empty())
print(li.length())

li.travel()

li.add(100)
li.append("gg")
li.insert(1,"ss")
li.add("start")
li.append("end")
print(li.is_empty())
print(li.length())

li.travel()
li.remove("end")
li.travel()

li.search("start")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值