函数说明:
- 初始化;
- 判空;
- 求长度;
- 插入节点:头插、尾插、随机插入;
- 遍历节点;
- 删除节点;
- 查找节点(搜索节点);
代码:
class Node(object):
def __init__(self, elem):
self.elem = elem
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 = self.__head
counter = 1
while cur.next != self.__head :
counter += 1
cur = cur.next
return counter
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 = node
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
node.next = self.__head
cur.next = node
def insert(self, pos, item):
"""
指定位置添加元素
@pos: 从0开始 例:insert(2,100)
因为不涉及尾部,所以不需要修改代码。
"""
if pos <= 0 :
self.add(item)
elif pos > (self.length() - 1):
self.append(item)
else:
node = Node(item)
pre = self.__head
count = 0
while count < (pos - 1):
pre = pre.next
count += 1
node.next = pre.next
pre.next = node
def search(self, item):
"""查找节点是否存在"""
if self.is_empty():
return False
cur = self.__head
while cur.next != self.__head:
if cur.elem == item:
return True
else:
cur = cur.next
if cur.elem == elem:
return True
return False
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 = 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