请编程实现一个对单链表进行基本操作的系统,主要包括表的创建、输入、查询、取 值、插入、删除和输出等操作。
时间: 2023-12-21 08:04:55 浏览: 21
由于没有具体的语言要求,以下提供一种Python语言的实现。
```python
# 定义节点类
class Node:
def __init__(self, value=None):
self.value = value
self.next = None
# 定义单链表类
class LinkedList:
def __init__(self):
self.head = Node() # 头节点
# 在链表末尾插入节点
def append(self, value):
new_node = Node(value)
cur_node = self.head
while cur_node.next != None:
cur_node = cur_node.next
cur_node.next = new_node
# 在链表指定位置插入节点
def insert(self, index, value):
if index >= self.length() or index < 0:
print("Error: Index out of range")
return
new_node = Node(value)
cur_node = self.head
cur_index = 0
while True:
last_node = cur_node
cur_node = cur_node.next
if cur_index == index:
last_node.next = new_node
new_node.next = cur_node
return
cur_index += 1
# 删除指定位置的节点
def delete(self, index):
if index >= self.length() or index < 0:
print("Error: Index out of range")
return
cur_node = self.head
cur_index = 0
while True:
last_node = cur_node
cur_node = cur_node.next
if cur_index == index:
last_node.next = cur_node.next
return
cur_index += 1
# 获取链表的长度
def length(self):
cur_node = self.head
length = 0
while cur_node.next != None:
cur_node = cur_node.next
length += 1
return length
# 查询指定位置的节点值
def get_value(self, index):
if index >= self.length() or index < 0:
print("Error: Index out of range")
return
cur_node = self.head
cur_index = 0
while True:
cur_node = cur_node.next
if cur_index == index:
return cur_node.value
cur_index += 1
# 输出链表中的所有节点值
def output(self):
cur_node = self.head
while cur_node.next != None:
cur_node = cur_node.next
print(cur_node.value)
# 创建单链表
linked_list = LinkedList()
# 输入节点值
n = int(input("请输入节点个数:"))
for i in range(n):
value = input("请输入节点值:")
linked_list.append(value)
# 输出链表
print("链表中的节点值为:")
linked_list.output()
# 查询节点
index = int(input("请输入要查询的节点位置:"))
print("第{}个节点的值为:{}".format(index, linked_list.get_value(index)))
# 插入节点
index = int(input("请输入要插入的位置:"))
value = input("请输入要插入的节点值:")
linked_list.insert(index, value)
print("插入节点后的链表:")
linked_list.output()
# 删除节点
index = int(input("请输入要删除的位置:"))
linked_list.delete(index)
print("删除节点后的链表:")
linked_list.output()
```
运行结果示例:
```
请输入节点个数:3
请输入节点值:1
请输入节点值:2
请输入节点值:3
链表中的节点值为:
1
2
3
请输入要查询的节点位置:1
第1个节点的值为:2
请输入要插入的位置:1
请输入要插入的节点值:4
插入节点后的链表:
1
4
2
3
请输入要删除的位置:2
删除节点后的链表:
1
4
3
```