使用c++分文件编写一个顺序表,并实现其基本操作
时间: 2024-05-09 22:20:46 浏览: 19
以下是使用C语言分文件编写一个顺序表的示例代码,包括了顺序表的基本操作:
1. 创建顺序表
2. 插入元素
3. 删除元素
4. 查找元素
5. 输出顺序表
其中,主文件为main.c,顺序表的头文件为SeqList.h,顺序表的实现文件为SeqList.c。
SeqList.h:
```c
#ifndef SEQLIST_H
#define SEQLIST_H
#define MAXSIZE 100 // 定义最大容量
typedef struct {
int data[MAXSIZE]; // 存放数据元素的数组
int length; // 当前长度
} SeqList;
// 初始化顺序表
void InitList(SeqList *L);
// 插入元素
int ListInsert(SeqList *L, int pos, int elem);
// 删除元素
int ListDelete(SeqList *L, int pos);
// 查找元素
int LocateElem(SeqList *L, int elem);
// 输出顺序表
void PrintList(SeqList *L);
#endif
```
SeqList.c:
```c
#include "SeqList.h"
#include <stdio.h>
// 初始化顺序表
void InitList(SeqList *L) {
L->length = 0;
}
// 插入元素
int ListInsert(SeqList *L, int pos, int elem) {
if (pos < 1 || pos > L->length + 1) {
return 0; // 插入位置不合法
}
if (L->length >= MAXSIZE) {
return 0; // 顺序表已满
}
for (int i = L->length; i >= pos; i--) {
L->data[i] = L->data[i-1]; // 将元素后移
}
L->data[pos-1] = elem; // 插入元素
L->length++; // 长度加1
return 1;
}
// 删除元素
int ListDelete(SeqList *L, int pos) {
if (pos < 1 || pos > L->length) {
return 0; // 删除位置不合法
}
for (int i = pos; i < L->length; i++) {
L->data[i-1] = L->data[i]; // 将元素前移
}
L->length--; // 长度减1
return 1;
}
// 查找元素
int LocateElem(SeqList *L, int elem) {
for (int i = 0; i < L->length; i++) {
if (L->data[i] == elem) {
return i+1; // 找到元素,返回位置
}
}
return 0; // 未找到元素
}
// 输出顺序表
void PrintList(SeqList *L) {
for (int i = 0; i < L->length; i++) {
printf("%d ", L->data[i]);
}
printf("\n");
}
```
main.c:
```c
#include "SeqList.h"
#include <stdio.h>
int main() {
SeqList L;
InitList(&L); // 初始化顺序表
// 插入元素
ListInsert(&L, 1, 10);
ListInsert(&L, 2, 20);
ListInsert(&L, 3, 30);
ListInsert(&L, 4, 40);
ListInsert(&L, 5, 50);
PrintList(&L); // 输出顺序表
// 删除元素
ListDelete(&L, 3);
PrintList(&L); // 输出顺序表
// 查找元素
int pos = LocateElem(&L, 20);
if (pos) {
printf("20 is at position %d\n", pos);
} else {
printf("20 is not found.\n");
}
return 0;
}
```