class Node(object):
def __init__(self.elem):
self.next=None
self.elem=elem
class SingleListLink(object):
"""单项单链表"""
def __init__(self,node=None):
self.head=node
if node:
node.next=node
def is_empty(self):
return self.head==None
def lenth(self):
"""链表长度"""
cur=self.head
count=0
while cur!=None:
count+=1
cur=cur.next
return count
def travel(self):
"""遍历整个链表"""
if self.is_empty():
return
cur=self.head
while cur.next!=self.head:
print(cur.elem,end=" ")
cur=cur.next
print(cur.elem)
def add(self,item):
"""链表头部添加元素"""
node=Node(item)
if self.is_empty():
node.next=self.head
self.head=node
else:
cur=self.head
while cur.next!=self.head:
cur=cur.next
node.next=self.head
self.head=node
cur.next=self.head
def append(self,item):
"""链表尾部添加元素"""
node=Node(item)
cur=self.head
if self.is_empty:
node.next=self.head
self.head=node
else:
while cur.next!=self.head:
cur=cur.next
cur.next=node
node.next=self.head
def insert(self,pos,item):
"""在指定位置添加元素"""
if pos<0:
self.add(item)
elif pos>(self.lenth-1):
self.append(item)
else:
node=Node(item)
pre=self.head
count=0
while count<(pos-1):
count+=1
pre=pre.next
node.next=pre.next
pre.next=node
def remove(self,item):
node=Node(item)
if self.is_empty():
return
cur=self.head
pre=None
while cur.next!=None:
if cur.elem==item:
if cur==self.head:
rear=self.head
while rear.next!=self.headad:
rear=rear.next
self.head=cur.next
rear.next=self.head
else:
pre.next=cur.next
return
else:
pre=cur
cur=cur.next
if cur.elem==item:
if cur==self.head:
self.head=None
else:
pre.next=self.head
def search(self,item):
if self.is_empty():
return False
cur=self.head
while cur.next!=self.head:
if cur.elem==item:
return True
cur=cur.next
if cur.elem==item:
return True
return False
cur=cur.next