Python单向循环链表及函数功能代码实现
#代码实现单向循环链表by Fan
#重点考虑尾节点被遗漏的情况
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):
print(self._head == None)
#获取链表的长度
def length(self):
if self._head == None:
return 0
else:
cur = self._head
count = 1
while cur.next != self._head:
cur = cur.next
count += 1
return count
#遍历链表
def travel(self):
if self._head == None:
return False
else:
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._head == None:
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._head == None:
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 < 1:
self.add(item)
elif pos > (self.length()-1):
self.append(item)
else:
node = Node(item)
pre = None
cur = self._head
count = 0
while count < pos:
pre = cur
cur = cur.next
count += 1
pre.next = node
node.next = cur
#查找特定元素是否存在
def search(self,item):
if self._head == None:
print("不在")
cur = self._head
while cur.next != self._head:
if cur.elem == item:
print("在")
return True
else:
cur = cur.next
if cur.elem == item:
print("在")
print("不在")
#删除某个特定元素
def shanchu(self,item):
pre = None
cur = self._head
while cur.next != self._head:
if cur.elem == item:
#判断该节点是否为头节点
if cur == self._head:
self._head = cur.next
cur_1 = self._head
while cur_1.next != cur:
cur_1 = cur_1.next
cur_1.next = self._head
return True
else:
pre.next = cur.next
return True
else:
pre = cur
cur = cur.next
#cur指向尾节点,最后一个节点无法进入循环,需要再进行考虑
if cur.elem == item:
if cur == self._head:
self._head = None
else:
pre.next = self._head
return False