把单链表改成单循环链表
时间: 2023-10-20 21:05:49 浏览: 116
单链表改成单循环链表的步骤如下:
1. 在单链表的尾节点处,将其指向头节点,形成环形。
2. 修改操作时需要注意,需要判断节点是否为头节点,以避免死循环。
3. 遍历操作需要判断是否到达了头节点,以避免死循环。
以下是具体的代码实现:
```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 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 remove_node(self, data):
if not self.head:
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
current = current.next
def traverse(self):
if not self.head:
return
current = self.head
while True:
print(current.data)
current = current.next
if current == self.head:
break
```
注意,这里的遍历操作是通过判断当前节点是否等于头节点来结束循环的。同时,在删除节点时,需要对头节点进行特殊处理,因为头节点的前驱节点是尾节点。
阅读全文