循环单链表 python_python实现单向循环链表数据结构及方法

首先要说明一下研究数据结构有什么用,可能就像高数之类的在生活中并没有多少用处,但是离不开他,很多大公司面试也会问这个东西;但是要落实到某一个具体的业务场景,我也不知道,但并不代表这些东西没用,也可能是这些模型只是为了让我们能理解更多有用的东西。

今天说的是单向循环链表,昨天说了单向链表,在此基础上我们说单向循环链表,其基本模型示图如下:

只不过在单向链表的基础上,最后一个节点纸箱头部,基本操作和单向链表基本一致,但是不同的是判断最后一个元素的标志不再是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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值