数据结构:设有一个带头结点的单循环链表,请编写程序从这个链表中删除值为x的结点。若链表中没有值为x的结点,则打印“没有找到该结点”。
时间: 2023-05-29 09:02:51 浏览: 48
以下是Python代码实现:
```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
class CircularLinkedList:
def __init__(self):
self.head = Node(None)
self.head.next = self.head
def insert(self, data):
new_node = Node(data)
if self.head.next == self.head:
self.head.next = new_node
new_node.next = self.head
else:
p = self.head.next
while p.next != self.head:
p = p.next
p.next = new_node
new_node.next = self.head
def delete(self, x):
if self.head.next == self.head:
print("没有找到该结点")
else:
p = self.head.next
pre = self.head
while p != self.head:
if p.data == x:
pre.next = p.next
del p
print("删除成功")
return
else:
pre = p
p = p.next
print("没有找到该结点")
def print_list(self):
if self.head.next == self.head:
print("链表为空")
else:
p = self.head.next
while p != self.head:
print(p.data, end=" ")
p = p.next
print()
```
接下来可以测试一下:
```python
if __name__ == '__main__':
cll = CircularLinkedList()
cll.insert(1)
cll.insert(2)
cll.insert(3)
cll.insert(4)
cll.insert(5)
cll.print_list() # 输出:1 2 3 4 5
cll.delete(3)
cll.print_list() # 输出:1 2 4 5
cll.delete(6) # 输出:没有找到该结点
```
最后的输出符合预期。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)