设计整数循环单链表的基本运算程序,并用相关数据进行测试
时间: 2024-05-03 10:21:19 浏览: 104
以下是循环单链表的基本运算程序的实现:
```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
class CircularLinkedList:
def __init__(self):
self.head = None
# 在链表尾部插入元素
def insert_at_end(self, data):
new_node = Node(data)
if self.head is None:
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 delete(self, data):
if self.head is None:
print("List is empty")
return
if self.head.data == data:
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 == data:
prev.next = current.next
return
print("Element not found in the list")
# 遍历链表
def traverse(self):
if self.head is None:
print("List is empty")
return
current = self.head
while current.next != self.head:
print(current.data, end=" ")
current = current.next
print(current.data)
# 创建循环单链表
llist = CircularLinkedList()
llist.insert_at_end(1)
llist.insert_at_end(2)
llist.insert_at_end(3)
# 遍历链表
llist.traverse() # Output: 1 2 3
# 删除元素
llist.delete(2)
# 遍历链表
llist.traverse() # Output: 1 3
```
上述代码创建了一个循环单链表类,其中包括了在链表尾部插入元素、删除指定元素和遍历链表的基本操作。对于循环单链表,需要特别注意在插入和删除节点时如何处理链表的头节点和尾节点。在测试代码中,我们创建了一个循环单链表并对其进行了遍历和删除元素的操作。
阅读全文