如何编写整数单链表的基本运算程序
时间: 2024-09-15 08:10:58 浏览: 44
编写整数单链表的基本运算是涉及创建链表节点、插入元素、删除元素以及遍历链表等基本操作。这里是一个简单的示例,我们将使用Python语言来说明:
首先,定义一个Node类,用于存储链表节点:
```python
class Node:
def __init__(self, value=0):
self.value = value
self.next = None
```
然后,创建链表类List,包含一些基础操作:
```python
class LinkedList:
def __init__(self):
self.head = None
# 插入节点到链表头部
def insert_at_beginning(self, value):
new_node = Node(value)
new_node.next = self.head
self.head = new_node
# 插入节点到指定位置
def insert_after(self, prev_node, value):
if not prev_node:
print("Previous node is invalid")
return
new_node = Node(value)
new_node.next = prev_node.next
prev_node.next = new_node
# 删除节点(如果找到,则删除)
def delete_by_value(self, value):
if not self.head:
return
if self.head.value == value:
self.head = self.head.next
return
current = self.head
while current.next and current.next.value != value:
current = current.next
if current.next:
current.next = current.next.next
# 遍历并打印链表
def traverse(self):
current = self.head
while current:
print(current.value, end=" -> ")
current = current.next
print("None")
```
你可以通过以下方式使用这个链表类:
```python
linked_list = LinkedList()
linked_list.insert_at_beginning(5)
linked_list.insert_after(linked_list.head.next, 3)
linked_list.insert_at_beginning(1)
linked_list.traverse() # 输出: 1 -> 5 -> 3 ->
linked_list.delete_by_value(3)
linked_list.traverse() # 输出: 1 -> 5 ->
```
阅读全文