python 创建循环链表
时间: 2023-05-16 20:06:11 浏览: 142
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):
current = self.head
if self.head is None:
print("List is empty")
else:
while current.next != self.head:
print(current.data, end=' ')
current = current.next
print(current.data)
clist = CircularLinkedList()
clist.add_node(1)
clist.add_node(2)
clist.add_node(3)
clist.add_node(4)
clist.display()
```
这段代码创建了一个循环链表,并添加了四个节点。最后,它打印出链表中的所有节点。
阅读全文