编写功能菜单程序,实现初始化、线性表遍历、插入、删除个基本操作,并求线性表长
时间: 2023-06-01 09:01:46 浏览: 91
这里提供一个Python实现的例子:
```
class LinkedList:
def __init__(self):
self.head = None
self.length = 0
def traverse(self):
if not self.head:
print("The linked list is empty!")
return
current = self.head
while current:
print(current.value, end=" ")
current = current.next
print()
def insert(self, value, index):
if index < 0 or index > self.length:
print("Invalid index!")
return
new_node = Node(value)
if index == 0:
new_node.next = self.head
self.head = new_node
else:
current = self.head
for i in range(index - 1):
current = current.next
new_node.next = current.next
current.next = new_node
self.length += 1
def delete(self, index):
if index < 0 or index >= self.length:
print("Invalid index!")
return
if index == 0:
self.head = self.head.next
else:
current = self.head
for i in range(index - 1):
current = current.next
current.next = current.next.next
self.length -= 1
def get_length(self):
return self.length
class Node:
def __init__(self, value):
self.value = value
self.next = None
def show_menu():
print("1. Initialize the linked list")
print("2. Traverse the linked list")
print("3. Insert a node")
print("4. Delete a node")
print("5. Get the length of linked list")
print("6. Exit")
choice = input("Please enter your choice: ")
return choice
if __name__ == "__main__":
linked_list = LinkedList()
while True:
choice = show_menu()
if choice == "1":
linked_list = LinkedList()
print("The linked list has been initialized!")
elif choice == "2":
linked_list.traverse()
elif choice == "3":
value = input("Please enter the value of the node: ")
index = int(input("Please enter the index to insert: "))
linked_list.insert(value, index)
print("The node has been inserted!")
elif choice == "4":
index = int(input("Please enter the index to delete: "))
linked_list.delete(index)
print("The node has been deleted!")
elif choice == "5":
print("The length of linked list is", linked_list.get_length())
elif choice == "6":
print("Goodbye!")
break
else:
print("Invalid choice!")
```
这个程序中,我们定义了一个链表类`LinkedList`和一个节点类`Node`。链表类中包含了初始化、遍历、插入、删除和获取长度等基本操作。在主函数中,我们通过循环不断地显示菜单,并根据用户的选择执行相应的操作。
阅读全文