用PYTHON写一个单顺序表具有增删与改查功能,并可以在命令框中实现增删与改查
时间: 2024-10-28 12:11:35 浏览: 26
在Python中,我们可以创建一个简单的线性数据结构,即单链表,来实现增删改查的功能。这里我们先定义链表节点和链表类,然后提供相应的操作方法:
```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
class SingleLinkedList:
def __init__(self):
self.head = None
# 插入元素到链表头部
def insert_at_start(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
# 插入元素到指定位置
def insert_at_position(self, position, data):
if not self.head or position <= 0:
print("Invalid position")
return
new_node = Node(data)
current = self.head
for _ in range(position - 1):
if current is None:
break
current = current.next
new_node.next = current.next
current.next = new_node
# 删除指定位置的元素
def delete_at_position(self, position):
if not self.head or position <= 0:
print("Invalid position")
return
if position == 1:
self.head = self.head.next
else:
current = self.head
for _ in range(position - 2):
if current.next is None:
break
current = current.next
current.next = current.next.next
# 修改指定位置的数据
def update_data(self, old_value, new_value, position):
if not self.head or position <= 0:
print("Invalid position")
return
current = self.head
for _ in range(position - 1):
if current.data == old_value:
current.data = new_value
break
current = current.next
# 打印链表内容
def display(self):
elements = []
current = self.head
while current:
elements.append(current.data)
current = current.next
print("Elements:", elements)
# 使用示例
sll = SingleLinkedList()
sll.insert_at_start(1)
sll.insert_at_position(2, 2)
sll.display() # 输出: Elements: [1, 2]
sll.update_data(2, 3, 2)
sll.display() # 输出: Elements: [1, 3]
sll.delete_at_position(1)
sll.display() # 输出: Elements: [3]
# 在命令行中运行上述代码片段
```
在命令行交互模式下,你可以通过导入此模块并实例化`SingleLinkedList`,然后直接调用上述提供的方法来进行增删改查操作。例如,通过输入`sll.insert_at_start(4)`这样的命令添加元素。
阅读全文