标签:python name 存在 app 实现 lis main search add
废话不说,直接上代码
#-*-coding=utf-8-*-
class Node(object):
"""节点"""
def __init__(self,elem):
self.elem=elem
self.next=None
class SingleLinkList(object):
"""单链表"""
def __init__(self,node=None):
self.__head = node
def is_empty(self):
"""判断是否为空"""
return self.__head==None
def length(self):
"""链表长度"""
#cur游标,用来移动遍历节点
cur = self.__head
#count记录数量
count=0
while cur!=None:
cur=cur.next
count+=1
return count
def travel(self):
"""遍历整个链表"""
cur=self.__head
while cur!=None:
print(cur.elem)
cur=cur.next
def add(self,item):
"""链表头部添加元素"""
node=Node(item)
node.next=self.__head
self.__head=node
def append(self,item):
"""链表尾部添加元素"""
if self.is_empty():
self.__head=Node(item)
else:
cur=self.__head
while cur.next!=None:
cur=cur.next
cur.next=Node(item)
def insert(self,pos,item):
"""指定位置添加元素"""
if pos<=0:
self.add(item)
elif pos>self.length()-1:
self.append(item)
else:
pre=self.__head
count=0
while count<pos-1:
pre=pre.next
count+=1
Node(item).next=pre.next
pre.next=Node(item)
def remove(self,item):
"""删除节点"""
cur=self.__head
pre=None
while cur!=None:
if cur.elem==item:
if cur==self.__head:
self.__head=cur.next
pre.next=cur.next
else:
pre=cur
cur=cur.next
def search(self,item):
"""查找节点是否存在"""
cur=self.__head
while cur!=None:
if cur.elem==item:
return True
else:
cur.next
return False
if __name__=="__main__":
ll=SingleLinkList()
print(ll.is_empty())
print(ll.length())
ll.append(1)
ll.append(2)
ll.append(3)
ll.append(4)
ll.append(5)
ll.append(6)
ll.append(7)
print(ll.is_empty())
print(ll.length())
ll.travel()
标签:python name 存在 app 实现 lis main search add
原文地址:https://www.cnblogs.com/linwenbin/p/10358550.html