首先要说明一下研究数据结构有什么用,可能就像高数之类的在生活中并没有多少用处,但是离不开他,很多大公司面试也会问这个东西;但是要落实到某一个具体的业务场景,我也不知道,但并不代表这些东西没用,也可能是这些模型只是为了让我们能理解更多有用的东西。
今天说的是单向循环链表,昨天说了单向链表,在此基础上我们说单向循环链表,其基本模型示图如下:
只不过在单向链表的基础上,最后一个节点纸箱头部,基本操作和单向链表基本一致,但是不同的是判断最后一个元素的标志不再是next==None而是next指向了头部指向的节点,这就是最后一个节点。定义基本节点对象和链条对象,源代码如下:
class Node(): #定义节点类
def __init__(self,item):
self.item = item
self.next = None
class SinCycLinkedList(): #定义循环链表类
def __init__(self):
self.head = None
def is_empty(self):
return None == self.head
def length(self):
if self.is_empty():
return 0
else:
cur = self.head
num = 1
while cur.next != self.head:
cur = cur.next
num += 1
return num
def ergotic(self): #遍历链表
if self.is_empty():
print(None)
else:
cur = self.head
while cur.next != self.head:
print(cur.item)
cur = cur.next
print(cur.item)
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.add(item)
else:
cur = self.head
while cur.next != self.head:
cur = cur.next
cur.next = node
node.next = self.head
def insert(self,index,item): #链表任意位置插入节点
if index == 0:
self.add(item)
elif index > self.length() -1:
self.append(item)
else:
cur = self.head
num = 1
while cur.next != self.head:
if index == num:
break
cur = cur.next
num += 1
node = Node(item)
node.next = cur.next
cur.next = node
def delet(self,index): #删除链表中下标为index的节点
if self.is_empty():
raise ValueError("null")
elif index == 0:
cur = self.head
if cur.next != self.head:
while cur.next != self.head :
cur = cur.next
cur.next = self.head.next
self.head = self.head.next
else:
cur = self.head
num = 1
while cur.next != self.head:
if num == index:
break
cur = cur.next
num += 1
cur.next = cur.next.next