数据结构与算法python-第四节
单向循环链表
定义
单链表的一个变形是单向循环链表,链表中最后一个节点的next域不再为None,而是指向链表的头节点
操作
- is_empty() 判断链表是否为空
- length() 链表长度
- travel() 遍历链表
- add(item) 头部添加链表
- append(item) 尾部添加链表
- insert(pos,elem) 指定位置插入链表
- remove(item) 删除元素
- search(item) 查找元素
单向循环列表的实现
class SingleNode(object):
'''单链表的结点'''
def __init__(self,elem):
# _item存放数据元素
self.elem = elem
# _next是下一个节点的标识
self.next = None
class SingleLinkList(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.is_empty():
return 0
# cur游标,用来移动遍历节点
cur = self.__head
# count记录数量
count = 1
while cur != self.__head:
count += 1
cur = cur.next
return count
def travel(self):
"""遍历整个链表"""
if self.is_empty():
return None
cur = self.__head
while cur.next != self.__head:
print(cur.elem,end=' ')
cur = cur.next
# 退出循环,cur指向尾节点,但尾节点的元素未打印
print(cur.elem)
def add(self,item):
"""链表头部添加元素"""
node = SingleNode(item)
if self.is_empty():
self.__head =node
node.next = node
else:
cur = self.__head
while cur.next != self.__head:
cur=cur.next
# 退出循环 cur 指向尾节点
node.next = self.__head
self.__head=node
cur.next = self.__head
def append(self,item):
"""链表尾部添加元素"""
node = SingleNode(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 = cur.next
cur.next = node
def insert(self,pos,item):
"""指定位置插入元素"""
"""
:param pos 从0开始
:item elem 元素值
"""
if pos <=0:
self.add(item)
elif pos>self.length()-1:
self.append(item)
else:
pre = self.__head
count =0
while count < pos - 1:
count +=1
pre = pre.next
# 当循环结束后,pre指向pos-1位置
node =SingleNode(item)
node.next = pre.next
pre.next =node
def remove(self,item):
"""删除节点"""
if self.is_empty():
return None
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 = rear.next
self.__head = cur.next
rear.next = self.__head
else:
pre.next = cur.next
return
else:
pre = cur
cur = cur.next
# 退出循环,cur指向尾节点
if cur.elem == item:
if cur == self.__head:
self.__head = None
else:
pre.next = cur.next
def search(self,item):
"""查找节点是否存在"""
cur = self.__head
while cur.next != None:
if cur.elem == item:
return True
else:
cur = cur.next
return False
if __name__ == "__main__":
ll = SingleLinkList()
print(ll.is_empty())
print(ll.length())
ll.append(1)
print(ll.is_empty())
print(ll.length())
ll.append(2)
ll.append(4)
ll.append(3)
ll.travel()
print(ll.length())
ll.add(8)
print()
ll.travel()
print()
ll.insert(-1,10)
ll.insert(1, 7)
ll.insert(10,99)
ll.travel()
print()
ll.remove(10)
ll.remove(99)
ll.travel()
ll.append(1)
ll.travel()
print()
ll.remove(1)
ll.travel()