Python的单循环链表
时间: 2023-11-05 08:57:54 浏览: 81
单循环链表是一种特殊的链表,它的最后一个节点的 next 指针指向头节点,形成一个环。
以下是 Python 实现单循环链表的代码:
```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
class CircularLinkedList:
def __init__(self):
self.head = None
def add_node(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 display(self):
if self.head is None:
print("List is empty")
else:
current = self.head
while current.next != self.head:
print(current.data, end=" ")
current = current.next
print(current.data, end=" ")
def remove_node(self, key):
if self.head is None:
print("List is empty")
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 search_node(self, key):
if self.head is None:
print("List is empty")
return
current = self.head
while current.next != self.head:
if current.data == key:
print("Node found")
return
current = current.next
if current.data == key:
print("Node found")
return
print("Node not found")
# Test the CircularLinkedList class
clist = CircularLinkedList()
clist.add_node(1)
clist.add_node(2)
clist.add_node(3)
clist.add_node(4)
print("Original List")
clist.display()
clist.remove_node(4)
print("\nList after removing node with data=4")
clist.display()
clist.search_node(2)
clist.search_node(5)
```
输出结果:
```
Original List
1 2 3 4
List after removing node with data=4
1 2 3
Node found
Node not found
```
上面的代码实现了单循环链表的基本操作,包括添加节点、删除节点、查找节点和显示链表。
阅读全文