class Node():
def __init__(self,item):
self.item=item
self.next=None
class SingleList():
def __init__(self):
self.__head=None
def is_empty(self):
return self.__head==None
def length(self):
if self.__head==None:
return 0
cur=self.__head
count=0
while cur:
count+=1
cur=cur.next
return count
#尾插法
def append(self,item):
node=Node(item)
if self.__head==None:
self.__head=node
else:
cur=self.__head
while cur.next:
cur=cur.next
cur.next=node
#头插法
def add(self,item):
node=Node(item)
node.next=self.__head
self.__head=node
#遍历
def travel(self):
cur=self.__head
if self.__head==None:
return
else:
while cur:
print(cur.item,end='')
cur=cur.next
#插入
def insert(self,item,pos):
node=Node(item)
count=0
cur=self.__head
if pos<=0:
self.add(item)
elif pos>self.length()-1:
self.append(item)
else:
while count<pos-1:
count+=1
cur=cur.next
node.next=cur.next
cur.next=node
#查询
def search(self,item):
if self.__head==None:
return
cur=self.__head
while cur:
if cur.item!=item:
cur=cur.next
else:
return True
return False
#移除
def remove(self,item):
if self.__head==None:
return
cur=self.__head
pre=None
while cur.item==item:
if cur==self.__head:
self.__head=cur.next
else:
pre.next=cur.next
break
pre=cur
cur=cur.next
#测试
if __name__=='__main__':
singlelist=SingleList()
singlelist.add(2)
singlelist.add(1)
singlelist.append(3)
singlelist.append(4)
singlelist.append(5)
singlelist.travel()
print()
singlelist.insert(6,3)
singlelist.travel()
print()
print(singlelist.search(5))
singlelist.remove(1)
singlelist.travel()
python数据结构-单链表
猜你喜欢
转载自blog.csdn.net/ustbclearwang/article/details/81411599
今日推荐
周排行