//库函数头文件包含
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
//函数状态码定义
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
typedef int Status;//状态量
//顺序表的存储结构定义
typedef int ElemType; //假设线性表中的元素均为整型
typedef struct {
ElemType* elem; //存储空间基地址
int length; //表中元素的个数
int listsize; //表容量大小
}SqList; //顺序表类型定义
//结构初始化与销毁操作
Status InitList(SqList &L) {
//初始化L为一个空的有序顺序表
L.elem=(ElemType *)malloc(LIST_INIT_SIZE*sizeof(ElemType));
if(!L.elem)exit(OVERFLOW);
L.listsize=LIST_INIT_SIZE;
L.length=0;
return OK;
}
//元素有序插入
Status ListInsert(SqList &L, ElemType e)
{
//扩容
if(L.length>=L.listsize)
L.elem=(ElemType *)realloc(L.elem,(L.length+10)*sizeof(ElemType));
if(!L.elem)return OVERFLOW;
//每插入一个元素,顺序表的长度加1
L.length++;
for(int i=0;i<L.length;i++)
if(*(L.elem+i)>e){
for(int j=L.length;j>i;j--)
*(L.elem+j)=*(L.elem+j-1);
*(L.elem+i)=e;
return OK;
}
*(L.elem+L.length-1)=e;
return OK;
}
//删除某一位置的元素
Status ListDelete(SqList &L,int pos,ElemType &e)
{
//若删除元素的位置超出顺序表长度
if(pos>L.length)
return OVERFLOW;
e=L.elem[pos-1];
for(int i=pos-1;i<L.length-1;i++)
L.elem[i]=L.elem[i+1];
L.length--;
return OK;
}
//定位e的位置
int ListLocate(SqList L,ElemType e)
{
for (int i=0;i<L.length;i++)
if (L.elem[i]==e)
return i+1;
//未找到元素e
return -1;
}
//顺序表输出
Status ListPrint(SqList L)
{
for (int i= 0;i<L.length-1;i++)
printf("%d ",L.elem[i]);
printf("%d\n",L.elem[L.length-1]);
}
//顺序表就地逆置
Status ListReverse(SqList &L)
{
int temp;
for(int i=0;i<L.length/2;i++){
temp=*(L.elem+i);
*(L.elem+i)=*(L.elem+L.length-i-1);
*(L.elem+L.length-i-1)=temp;
}
return OK;
}
//测试主函数
int main() {
SqList L;
if (InitList(L) != OK) {
printf("InitList_Sq: 初始化失败!!!\n");
return -1;
}
for (int i = 1; i <= 10; ++i)
ListInsert(L, i);
int operationNumber; //操作次数
scanf("%d", &operationNumber);
while (operationNumber != 0) {
int operationType; //操作种类
scanf("%d", &operationType);
if (operationType == 1) { //增加操作
int pos, elem;
scanf("%d",&elem);
ListInsert(L,elem);
}
else if (operationType == 2) { //删除操作
int pos;
ElemType elem;
scanf("%d", &pos);
ListDelete(L, pos, elem);
printf("%d\n", elem);
}
else if (operationType == 3) { //查找定位操作
ElemType elem;
scanf("%d", &elem);
int pos = ListLocate(L, elem);
if (pos >= 1 && pos <= L.length)
printf("%d\n", pos);
else
printf("NOT FIND!\n");
}
else if (operationType == 4) { //输出操作
ListPrint(L);
else if (operationType == 5) { //逆置操作
ListReverse(L);
}
operationNumber--;
}
return 0;
}
顺序表的基本操作
最新推荐文章于 2024-10-25 20:58:30 发布