废话不多说,直接上代码:
#-*-coding=utf-8-*-
class Node(object):
"""节点"""
def __init__(self,elem):
self.elem=elem
self.next=None
class SingleCircleLink(object):
"""单链表"""
def __init__(self,node=None):
self.__head = node
if node:
node.next=node
def is_empty(self):
"""判断是否为空"""
return self.__head==None
def length(self):
"""链表长度"""
if self.__head==None:
return 0
#cur游标,用来移动遍历节点
cur = self.__head
#count记录数量
count=1
while cur.next!=self.__head:
cur=cur.next
count+=1
return count
def travel(self):
"""遍历整个链表"""
if self.is_empty():
return
cur=self.__head
while cur.next!=self.__head:
print(cur.elem)
cur=cur.next
print(cur.elem)
def add(self,item):
"""链表头部添加元素"""
node=Node(item)
if self.is_empty():
self.__head=node
node.next=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)
if self.is_empty():
self.__head=node
node.next=node
else:
cur=self.__head
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.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):
"""删除节点"""
if self.is_empty():
return
cur=self.__head
pre=None
while cur.next!=self.__head:
if cur.elem==item:
if cur==self.__head:
rear=self.__head
while rear.next!=self.__head:
rear=cur.next
self.__head=cur.next
rear.next=self.__head
pre.next=cur.next
else:
pre=cur
cur=cur.next
def search(self,item):
"""查找节点是否存在"""
if self.is_empty():
return False
else:
cur=self.__head
while cur.next!=self.__head:
if cur.elem==item:
return True
else:
cur=cur.next
if cur.elem==item:
return True
return False
if __name__=="__main__":
ll=SingleCircleLink()
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()