实现线性表的插入、删除、求表长、查找给定值 e、查找第 i 个位置元素 等基本操作,要求编写的程序以菜单方式工作
时间: 2024-10-24 17:12:49 浏览: 44
实验一 线性表基本操作的编程实现
5星 · 资源好评率100%
要实现一个简单的线性表(如数组或链表)的基本操作,你可以使用Java编写一个命令行界面的程序。这里我会给出一个基于数组实现的简单示例,包括插入、删除、求表长、查找和显示元素等操作。我们将使用一个`ArrayList`来存储数据,因为它的大小可变并且提供了方便的方法进行这些操作。
```java
import java.util.ArrayList;
import java.util.Scanner;
class LinearList {
private ArrayList<Integer> list;
public LinearList() {
list = new ArrayList<>();
}
// 插入元素
public void insert(int value, int position) {
if (position >= 0 && position <= list.size()) {
list.add(position, value);
} else {
System.out.println("Invalid position.");
}
}
// 删除元素
public void delete(int position) {
if (position >= 0 && position < list.size()) {
list.remove(position);
} else {
System.out.println("Invalid position.");
}
}
// 求表长
public int length() {
return list.size();
}
// 查找元素
public boolean search(int value) {
return list.contains(value);
}
// 查找第i个元素
public int get(int index) {
if (index >= 0 && index < list.size()) {
return list.get(index);
} else {
System.out.println("Invalid index.");
return -1; // 返回默认值或者抛异常取决于需求
}
}
// 显示列表元素
public void display() {
System.out.print("Linear List: ");
for (int i : list) {
System.out.print(i + " ");
}
System.out.println();
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
LinearList linearList = new LinearList();
while (true) {
System.out.println("\n1. Insert");
System.out.println("2. Delete");
System.out.println("3. Check Length");
System.out.println("4. Search");
System.out.println("5. Get Element by Index");
System.out.println("6. Display");
System.out.println("7. Exit");
System.out.print("Enter your choice: ");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.print("Position and Value: ");
int pos = scanner.nextInt(), val = scanner.nextInt();
linearList.insert(val, pos);
break;
case 2:
System.out.print("Position to delete: ");
pos = scanner.nextInt();
linearList.delete(pos);
break;
case 3:
System.out.println("Length of the list: " + linearList.length());
break;
case 4:
System.out.print("Value to search: ");
int searchVal = scanner.nextInt();
boolean found = linearList.search(searchVal);
if (found) {
System.out.println("Found");
} else {
System.out.println("Not Found");
}
break;
case 5:
System.out.print("Index: ");
int idx = scanner.nextInt();
int element = linearList.get(idx);
if (element != -1) {
System.out.println("Element at index " + idx + ": " + element);
}
break;
case 6:
linearList.display();
break;
case 7:
System.out.println("Exiting...");
scanner.close();
return;
default:
System.out.println("Invalid choice. Please try again.");
}
}
}
}
```
这个程序提供了一个简单的菜单,用户可以根据指示执行相应的操作。你可以根据需要修改和扩展这个程序,比如添加错误处理或优化用户体验。如果你对其他数据结构(如链表)有兴趣,可以替换`ArrayList`为`LinkedList`并相应地调整方法实现。
阅读全文