当选择删除功能时,从键盘读入欲删除的元素位置或元素值,按指定方式删除;当选择插入功能时,从键盘读入新元素值和被插入位置,在指定位置插入;当选择查找功能时,从键盘读入欲查找的元素值,返回其位置序号。
时间: 2023-05-27 18:04:50 浏览: 44
以下是一个示例代码,实现了一个简单的线性表,包括插入、删除和查找功能:
```
#include <stdio.h>
#define MAX_SIZE 100
typedef struct {
int data[MAX_SIZE];
int length;
} SeqList;
int locate(SeqList *L, int x) {
for (int i = 0; i < L->length; i++) {
if (L->data[i] == x) {
return i;
}
}
return -1;
}
void insert(SeqList *L, int x, int pos) {
if (pos < 0 || pos > L->length) {
printf("Invalid position!\n");
return;
}
if (L->length >= MAX_SIZE) {
printf("List overflow!\n");
return;
}
for (int i = L->length; i > pos; i--) {
L->data[i] = L->data[i-1];
}
L->data[pos] = x;
L->length++;
}
void delete(SeqList *L, int x) {
int pos = locate(L, x);
if (pos == -1) {
printf("Element not found!\n");
return;
}
for (int i = pos; i < L->length-1; i++) {
L->data[i] = L->data[i+1];
}
L->length--;
}
void print_list(SeqList *L) {
printf("List:");
for (int i = 0; i < L->length; i++) {
printf(" %d", L->data[i]);
}
printf("\n");
}
int main() {
SeqList L;
L.length = 0;
int choice, x, pos;
while (1) {
printf("1: insert, 2: delete, 3: search, 4: print, 5: quit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter element to insert: ");
scanf("%d", &x);
printf("Enter position to insert: ");
scanf("%d", &pos);
insert(&L, x, pos);
break;
case 2:
printf("Enter element to delete: ");
scanf("%d", &x);
delete(&L, x);
break;
case 3:
printf("Enter element to search: ");
scanf("%d", &x);
pos = locate(&L, x);
if (pos == -1) {
printf("Element not found!\n");
} else {
printf("Element found at position %d.\n", pos);
}
break;
case 4:
print_list(&L);
break;
case 5:
return 0;
default:
printf("Invalid choice!\n");
break;
}
}
}
```
在程序运行时,用户可以根据菜单选择插入、删除、查找或打印线性表,例如:
```
1: insert, 2: delete, 3: search, 4: print, 5: quit
Enter your choice: 1
Enter element to insert: 2
Enter position to insert: 0
List: 2
1: insert, 2: delete, 3: search, 4: print, 5: quit
Enter your choice: 1
Enter element to insert: 3
Enter position to insert: 1
List: 2 3
1: insert, 2: delete, 3: search, 4: print, 5: quit
Enter your choice: 1
Enter element to insert: 1
Enter position to insert: 0
List: 1 2 3
1: insert, 2: delete, 3: search, 4: print, 5: quit
Enter your choice: 2
Enter element to delete: 2
List: 1 3
1: insert, 2: delete, 3: search, 4: print, 5: quit
Enter your choice: 3
Enter element to search: 3
Element found at position 1.
1: insert, 2: delete, 3: search, 4: print, 5: quit
Enter your choice: 4
List: 1 3
1: insert, 2: delete, 3: search, 4: print, 5: quit
Enter your choice: 5
```
阅读全文