输出说明: 创建的链表; 删除后的链表。
时间: 2024-06-13 17:09:33 浏览: 71
链表的创建、查找、输出、删除
循环链表输出示例:
```python
# 定义循环链表节点类
class Node:
def __init__(self, data):
self.data = data
self.next = None
# 定义循环链表类
class CircularLinkedList:
def __init__(self):
self.head = None
# 在链表尾部添加节点
def append(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 print_list(self):
current = self.head
if not current:
print("链表为空")
return
while True:
print(current.data, end=" ")
current = current.next
if current == self.head:
break
print("->", end=" ")
# 创建循环链表
cll = CircularLinkedList()
cll.append(1)
cll.append(2)
cll.append(3)
cll.append(4)
cll.append(5)
# 输出循环链表
cll.print_list() # 输出:1 -> 2 -> 3 -> 4 -> 5 ->
```
单向链表删除节点示例:
```python
# 定义单向链表节点类
class Node:
def __init__(self, data):
self.data = data
self.next = None
# 定义单向链表类
class LinkedList:
def __init__(self):
self.head = None
# 在链表尾部添加节点
def append(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
else:
current = self.head
while current.next:
current = current.next
current.next = new_node
# 删除链表中值为value的节点
def delete_node(self, value):
if not self.head:
return None
if self.head.data == value:
self.head = self.head.next
return self.head
current = self.head
while current.next:
if current.next.data == value:
current.next = current.next.next
return self.head
current = current.next
return self.head
# 输出链表
def print_list(self):
current = self.head
if not current:
print("链表为空")
return
while current:
print(current.data, end=" ")
current = current.next
if current:
print("->", end=" ")
# 创建单向链表
ll = LinkedList()
ll.append(1)
ll.append(2)
ll.append(3)
ll.append(2)
ll.append(5)
# 删除值为2的节点
ll.delete_node(2)
# 输出链表
ll.print_list() # 输出:1 -> 3 -> 5 ->
```
阅读全文