整数顺序表的建立、查找、插入、删除、输出程序(线性表的顺序存储实现),表中不允许有重复数据,保存为SqList文件,可手动输入顺序表
时间: 2024-05-13 07:15:07 浏览: 102
以下是基于C语言的整数顺序表建立、查找、插入、删除、输出程序:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef struct {
int elem[MAXSIZE];
int length;
} SqList;
void initList(SqList *L) {
L->length = 0;
}
int locateElem(SqList L, int e) {
for (int i = 0; i < L.length; i++) {
if (L.elem[i] == e) {
return i;
}
}
return -1;
}
int insertElem(SqList *L, int e) {
if (L->length == MAXSIZE) {
return 0;
}
if (locateElem(*L, e) != -1) {
return 0;
}
L->elem[L->length++] = e;
return 1;
}
int deleteElem(SqList *L, int e) {
int pos = locateElem(*L, e);
if (pos == -1) {
return 0;
}
for (int i = pos; i < L->length - 1; i++) {
L->elem[i] = L->elem[i + 1];
}
L->length--;
return 1;
}
void printList(SqList L) {
for (int i = 0; i < L.length; i++) {
printf("%d ", L.elem[i]);
}
printf("\n");
}
void saveList(SqList L) {
FILE *fp;
fp = fopen("SqList.txt", "w");
for (int i = 0; i < L.length; i++) {
fprintf(fp, "%d ", L.elem[i]);
}
fclose(fp);
}
int main() {
SqList list;
initList(&list);
int choice, elem;
while (1) {
printf("1. Insert element to list\n");
printf("2. Delete element from list\n");
printf("3. Search element from list\n");
printf("4. Print all elements of list\n");
printf("5. Save list to file\n");
printf("6. Quit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter element to insert: ");
scanf("%d", &elem);
if (insertElem(&list, elem)) {
printf("Insert successfully!\n");
} else {
printf("Insert failed! Element may exist or list is full.\n");
}
break;
case 2:
printf("Enter element to delete: ");
scanf("%d", &elem);
if (deleteElem(&list, elem)) {
printf("Delete successfully!\n");
} else {
printf("Delete failed! Element may not exist.\n");
}
break;
case 3:
printf("Enter element to search: ");
scanf("%d", &elem);
int pos = locateElem(list, elem);
if (pos == -1) {
printf("Element not found.\n");
} else {
printf("Element found at position %d.\n", pos + 1);
}
break;
case 4:
printf("Elements in list: ");
printList(list);
break;
case 5:
printf("Saving list to file...\n");
saveList(list);
printf("Save successfully!\n");
break;
case 6:
printf("Goodbye!\n");
exit(0);
default:
printf("Invalid choice! Please try again.\n");
break;
}
}
return 0;
}
```
程序中使用了一个结构体 `SqList` 来表示顺序表,其中 `elem` 数组用来存储元素,`length` 表示元素个数。实现了初始化函数 `initList`,查找函数 `locateElem`,插入函数 `insertElem`,删除函数 `deleteElem`,输出函数 `printList`,保存函数 `saveList`,以及一个简单的交互菜单来进行操作。最终结果将保存到名为 `SqList.txt` 的文件中。
阅读全文