编写功能菜单程序,实现初始化、线性表遍历、插入、删除4个基本操作
时间: 2023-05-19 13:01:13 浏览: 59
好的,以下是一个简单的功能菜单程序,实现了初始化、线性表遍历、插入、删除4个基本操作:
```
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef struct {
int data[MAXSIZE];
int length;
} List;
void initList(List *L) {
L->length = 0;
}
void traverseList(List L) {
int i;
for (i = 0; i < L.length; i++) {
printf("%d ", L.data[i]);
}
printf("\n");
}
int insertList(List *L, int pos, int value) {
int i;
if (pos < 1 || pos > L->length + 1 || L->length == MAXSIZE) {
return 0;
}
for (i = L->length - 1; i >= pos - 1; i--) {
L->data[i + 1] = L->data[i];
}
L->data[pos - 1] = value;
L->length++;
return 1;
}
int deleteList(List *L, int pos) {
int i;
if (pos < 1 || pos > L->length) {
return 0;
}
for (i = pos - 1; i < L->length - 1; i++) {
L->data[i] = L->data[i + 1];
}
L->length--;
return 1;
}
int main() {
List L;
int choice, pos, value;
initList(&L);
while (1) {
printf("1. Traverse list\n");
printf("2. Insert element\n");
printf("3. Delete element\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
traverseList(L);
break;
case 2:
printf("Enter position and value: ");
scanf("%d %d", &pos, &value);
if (insertList(&L, pos, value)) {
printf("Insert successful\n");
} else {
printf("Insert failed\n");
}
break;
case 3:
printf("Enter position: ");
scanf("%d", &pos);
if (deleteList(&L, pos)) {
printf("Delete successful\n");
} else {
printf("Delete failed\n");
}
break;
case 4:
exit(0);
default:
printf("Invalid choice\n");
}
}
return 0;
}
```
希望这个程序能够帮到你!
阅读全文