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")
python 单链表
最新推荐文章于 2021-04-09 16:18:01 发布