编写功能菜单程序,实现初始化线性表遍历、插入、删除4个基本操作
时间: 2023-05-14 16:07:18 浏览: 113
好的,这是一个常见的线性表操作,以下是一个简单的实现:
```
#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;
initList(&L);
insertList(&L, 1, 1);
insertList(&L, 2, 2);
insertList(&L, 3, 3);
traverseList(L);
deleteList(&L, 2);
traverseList(L);
return 0;
}
```
这个程序实现了初始化线性表、遍历、插入和删除操作。其中,initList() 函数用于初始化线性表,traverseList() 函数用于遍历线性表并输出每个元素,insertList() 函数用于在指定位置插入一个元素,deleteList() 函数用于删除指定位置的元素。
阅读全文
相关推荐


















