请编写程序实现单链表插入、删除结点等基本算法。给定一个单链表和一系列插入、删除结点的操作序列,输出实施上述操作后的链表。单链表数据域值为整数。
时间: 2023-02-27 15:58:12 浏览: 170
以下是 Python 代码实现:
```
class Node:
def __init__(self, val):
self.val = val
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insert_node(self, val):
new_node = Node(val)
new_node.next = self.head
self.head = new_node
def delete_node(self, val):
prev = None
curr = self.head
while curr:
if curr.val == val:
if prev:
prev.next = curr.next
else:
self.head = curr.next
return
prev = curr
curr = curr.next
def print_list(self):
curr = self.head
while curr:
print(curr.val, end=' ')
curr = curr.next
print('')
linked_list = LinkedList()
linked_list.insert_node(1)
linked_list.insert_node(2)
linked_list.insert_node(3)
linked_list.print_list() # Output: 3 2 1
linked_list.delete_node(2)
linked_list.print_list() # Output: 3 1
```
上面的代码实现了单链表的插入结点和删除结点算法,并且提供了一个 `print_list` 函数以便查看结果。在给定的操作序列中,可以通过调用 `insert_node` 函数来实现插入结点操作,通过调用 `delete_node` 函数来实现删除结点操作。最终,输出实施上述操作后的链表可以通过调用 `print_list` 函数实现。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)