生成一个循环链表,python
时间: 2023-11-06 18:09:12 浏览: 31
以下是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 the list is empty
if self.head is None:
self.head = new_node
new_node.next = self.head
else:
# Traverse to the last node
last_node = self.head
while last_node.next != self.head:
last_node = last_node.next
# Add the new node to the end
last_node.next = new_node
new_node.next = self.head
def display(self):
current_node = self.head
if current_node is None:
print("List is empty")
else:
print("Nodes in the circular linked list:")
while True:
print(current_node.data)
current_node = current_node.next
if current_node == self.head:
break
# Create a circular linked list
clist = CircularLinkedList()
# Add nodes to the list
clist.add_node(1)
clist.add_node(2)
clist.add_node(3)
clist.add_node(4)
# Display the list
clist.display()
```
这个循环链表包含了4个节点,其中每个节点都指向下一个节点,最后一个节点指向第一个节点,从而形成一个循环。