循环链表的基本操作代码
时间: 2023-12-18 20:26:07 浏览: 33
循环链表是一种特殊的链表,它的最后一个节点指向第一个节点,形成一个环。循环链表的基本操作包括创建、插入、删除和遍历等。
下面是循环链表的基本操作代码:
```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
class CircularLinkedList:
def __init__(self):
self.head = None
# 在链表末尾插入节点
def append(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
new_node.next = self.head
else:
current = self.head
while current.next != self.head:
current = current.next
current.next = new_node
new_node.next = self.head
# 在链表头部插入节点
def prepend(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
new_node.next = self.head
else:
current = self.head
while current.next != self.head:
current = current.next
current.next = new_node
new_node.next = self.head
self.head = new_node
# 删除指定节点
def remove(self, key):
if not self.head:
return
if self.head.data == key:
current = self.head
while current.next != self.head:
current = current.next
current.next = self.head.next
self.head = self.head.next
else:
current = self.head
prev = None
while current.next != self.head:
prev = current
current = current.next
if current.data == key:
prev.next = current.next
current = current.next
# 遍历链表
def print_list(self):
if not self.head:
return
current = self.head
while current.next != self.head:
print(current.data)
current = current.next
print(current.data)
# 创建循环链表
cllist = CircularLinkedList()
cllist.append(1)
cllist.append(2)
cllist.append(3)
cllist.append(4)
# 遍历循环链表
cllist.print_list()
# 在头部插入节点
cllist.prepend(0)
cllist.print_list()
# 删除节点
cllist.remove(3)
cllist.print_list()
```