L是一个顺序表,函数Status ListInsert_Sq(SqList &L, int pos, ElemType e)是在顺序表的pos位置插入一个元素e(pos应该从1开始),函数Status ListDelete_Sq(SqList &L, int pos, ElemType &e)是删除顺序表的pos位置的元素并用引用型参数e带回(pos应该从1开始),函数int ListLocate_Sq(SqList L, ElemType e)是查询元素e在顺序表的位次并返回(如有多个取第一个位置,返回的是位次,从1开始,不存在则返回0),函数void ListPrint_Sq(SqList L)是输出顺序表元素。实现时需考虑表满扩容的问题。
Code: (c++)
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
//函数状态码定义
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef int Status;
//顺序表的存储结构定义
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
typedef int ElemType; //假设线性表中的元素均为整型
typedef struct{
ElemType* elem; //存储空间基地址
int length; //表中元素的个数
int listsize; //表容量大小
}SqList; //顺序表类型定义
//插入操作
Status ListInsert_Sq(SqList &L, int pos, ElemType e)
{
if(L.length == L.listsize) //线性表已经满了,扩容
{
ElemType *p;
p = (ElemType*) realloc((ElemType*)L.elem, sizeof(ElemType)*(L.listsize + LISTINCREMENT));
if(!p) return OVERFLOW;
L.elem = p;
L.listsize += LISTINCREMENT;
}
//开始转移元素
ElemType* p = L.elem;
for(int i = L.length+1; i >= pos; i--)
*(p+i) = *(p+i-1);
*(p + pos) = e;
L.length++;
return OK;
}
//删除操作
Status ListDelete_Sq(SqList &L, int pos, ElemType &e)
{
if(pos <= 0 || pos > L.length) return ERROR; //不合法的操作
//输出要删除的元素,传引用,只能用地址来获得原来的值,这应该就是地址拷贝吧(深拷贝)。
ElemType *p = &(L.elem[pos]);
e = *(p);
for(int i = pos; i < L.length; i++)
{
*(L.elem+i) = *(L.elem+i+1);
}
L.length--;
return OK;
}
//查找操作
int ListLocate_Sq(SqList L, ElemType e)
{
for(int i = 1; i <= L.length; i++)
{
if(*(L.elem+i) == e)
return i;
}
return 0; //没有查到
}
//输出操作
void ListPrint_Sq(SqList L)
{
for(int i = 1; i <= L.length; i++)
{
if(i == 1) printf("%d", *(L.elem+i));
else printf(" %d",*(L.elem+i));
}
printf("\n");
}
//结构初始化与销毁操作
Status InitList_Sq(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;
}
int main() {
SqList L;
if(InitList_Sq(L)!= OK) {
printf("InitList_Sq: 初始化失败!!!\n");
return -1;
}
for(int i = 1; i <= 10; ++ i)
ListInsert_Sq(L, i, i);
int operationNumber; //操作次数
scanf("%d", &operationNumber);
while(operationNumber != 0) {
int operationType; //操作种类
scanf("%d", & operationType);
if(operationType == 1) { //增加操作
int pos, elem;
scanf("%d%d", &pos, &elem);
ListInsert_Sq(L, pos, elem);
} else if(operationType == 2) { //删除操作
int pos; ElemType elem;
scanf("%d", &pos);
ListDelete_Sq(L, pos, elem);
printf("%d\n", elem);
} else if(operationType == 3) { //查找定位操作
ElemType elem;
scanf("%d", &elem);
int pos = ListLocate_Sq(L, elem);
if(pos >= 1 && pos <= L.length)
printf("%d\n", pos);
else
printf("NOT FIND!\n");
} else if(operationType == 4) { //输出操作
ListPrint_Sq(L);
}
operationNumber--;
}
return 0;
}