文章目录
1、概念2、操作3、python实现操作
1、概念
单向循环链表是单链表的一个变型,链表最后的一个节点的next域不再为None,而是指向链表的头节点
2、操作
is_empty() 判断链表是否为空length() 返回链表的长度tracel() 遍历add(item) 在头部添加一个节点append(item) 在尾部添加一个节点insert(pos,item) 在指定位置pos添加节点remove(item) 删除一个节点search(item) 查找结点是否存在
3、python实现操作
class Node(object):
def __init__(self
,elem
):
self
.elem
=elem
self
.next=None
class SingleCycleLink(object):
def __init__(self
,node
=None):
self
.__head
=node
if node
:
node
.next=node
def is_empty(self
):
cur
=self
.__head
return self
.__head
==None
def length(self
):
if self
.is_empty
():
return 0
cur
=self
.__head
count
=1
while cur
.next != self
.__head
:
count
+= 1
cur
=cur
.next
return count
def travel(self
):
if self
.is_empty
():
return
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
.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=self
.__head
else:
cur
=self
.__head
while cur
.next != self
.__head
:
cur
=cur
.next
cur
.next=node
node
.next=self
.__head
def insert(self
,pos
,item
):
node
=Node
(item
)
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
node
.next=pre
.next
pre
.next=node
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=cur
.next
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
==item
:
return True
return False
测试:
if __name__
== '__main__':
sincyclink
=SingleCycleLink
()
print('此时链表是否为空', sincyclink
.is_empty
())
print('此时链表长度为:', sincyclink
.length
())
sincyclink
.append
(1)
print('此时链表是否为空', sincyclink
.is_empty
())
print('此时链表长度为:', sincyclink
.length
())
sincyclink
.append
(2)
sincyclink
.add
(8)
sincyclink
.append
(3)
sincyclink
.append
(4)
sincyclink
.travel
()
sincyclink
.insert
(-1,9)
sincyclink
.travel
()
sincyclink
.insert
(-1,100)
sincyclink
.travel
()
sincyclink
.insert
(10,100)
sincyclink
.travel
()
sincyclink
.remove
(100)
sincyclink
.travel
()
结果:
此时链表是否为空
True
此时链表长度为:
0
此时链表是否为空
False
此时链表长度为:
1
8 1 2 3 4
9 8 1 2 3 4
100 9 8 1 2 3 4
100 9 8 1 2 3 4 100
9 8 1 2 3 4 100