📅  最后修改于: 2023-12-03 15:40:00.816000             🧑  作者: Mango
循环链表是一种特殊的链表,与普通链表相比,循环链表的头结点和尾结点是相连的。这就使得循环链表具有了环形结构,在操作循环链表时需要特别注意这种特殊的结构。
创建一个循环链表需要先创建一个头结点,然后将头结点的 next
指向自己,即可形成一个空的循环链表。如下所示:
class Node:
def __init__(self, data):
self.data = data
self.next = None
class CircularLinkedList:
def __init__(self):
self.head = Node(None)
self.head.next = self.head
在循环链表中插入元素分为两种情况,分别是头插法和尾插法。头插法是将新节点插入到头结点后面,尾插法是将新节点插入到末尾节点之前。
class CircularLinkedList:
...
def insert_at_beginning(self, data):
new_node = Node(data)
new_node.next = self.head.next
self.head.next = new_node
class CircularLinkedList:
...
def insert_at_end(self, data):
new_node = Node(data)
current = self.head
while current.next != self.head:
current = current.next
current.next = new_node
new_node.next = self.head
在循环链表中删除元素同样分为两种情况,分别是删除指定节点和删除头节点。
class CircularLinkedList:
...
def delete_node(self, key):
current = self.head.next
prev = self.head
while current != self.head:
if current.data == key:
prev.next = current.next
current = None
return
prev = current
current = current.next
class LinkedList:
...
def delete_at_beginning(self):
if self.head.next != self.head:
current = self.head.next
self.head.next = current.next
current = None
else:
print("Linked list is empty")
输出循环链表需要从头结点开始遍历,直到再次回到头结点为止。
class CircularLinkedList:
...
def print_list(self):
current = self.head.next
while current != self.head:
print(current.data, end=' ')
current = current.next
以上便是关于循环链表的相关介绍,希望对程序员们有所帮助。