用python编写一个单顺序表具有增删改查功能,并能在命令框中实现增删改查
时间: 2024-10-28 20:15:27 浏览: 10
当然可以,我们首先需要创建一个简单的单链表结构,然后为其添加`insert`, `delete`, `update`, 和 `search`方法。这里是一个基础的Python实现:
```python
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class SinglyLinkedList:
def __init__(self):
self.head = None
# 插入节点
def insert(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
# 删除节点
def delete(self, key):
if not self.head:
return "List is empty"
elif self.head.data == key:
self.head = self.head.next
return f"Deleted {key}"
else:
current = self.head
while current.next and current.next.data != key:
current = current.next
if current.next:
current.next = current.next.next
return f"Deleted {key}"
else:
return f"{key} not found in the list"
# 更新节点值
def update(self, old_key, new_data):
current = self.head
while current:
if current.data == old_key:
current.data = new_data
return f"Updated {old_key} to {new_data}"
current = current.next
return f"{old_key} not found in the list"
# 搜索节点
def search(self, key):
current = self.head
while current:
if current.data == key:
return f"Found {key}"
current = current.next
return f"{key} not found in the list"
# 在命令行演示操作
if __name__ == "__main__":
sll = SinglyLinkedList()
sll.insert(1)
sll.insert(2)
print(sll.search(2)) # 查询节点
sll.update(2, 3) # 更新节点值
print(sll.delete(1)) # 删除节点
```
当你运行这个脚本时,可以在命令行里通过调用SinglyLinkedList类的方法来进行增删改查操作。例如,你可以输入`sll.insert(4)`来添加元素。
阅读全文