定义结构 SqList
typedef int ElemType;
typedef struct{
ElemType *elem;
int length;
int listsize;
}SqList;
预定义常量和类型
#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
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
typedef int Status; //Status是函数的类型,其值是函数结果状态的代码
构造一个空的顺序表
Status Init_Sq(SqList& L){
L.elem = (ElemType*)malloc(LIST_INIT_SIZE*sizeof(ElemType));
if(!L.elem) exit (OVERFLOW); //存储分配失败
L.length = 0; //空表长度为0
L.listsize = LIST_INIT_SIZE; //初始存储容量
return OK;
}
实现插入操作
在顺序线性表L中第i个位置之前插入新的元素e
Status ListInsert_Sq(SqList &L, int i, ElemType e){
//i的合法值为1<= i<=ListLength_Sq(L)+1
ElemType *newbase;
int *p;
int *q;
if(i<1 || i>L.length + 1) return ERROR;
if(L.length >= L.listsize){
newbase = (ElemType*)realloc(L.elem,(L.listsize + LISTINCREMENT)*sizeof(ElemType));
if(!newbase) exit(OVERFLOW);
L.elem = newbase; //新的基地址
L.listsize += LISTINCREMENT;
}
q = &(L.elem[i-1]);
for(p = &(L.elem[L.length-1]); p>=q;--p) *(p+1) = *p; // 插入位置以及之后的元素右移
*q = e; // 插入e
++L.length; //表长加1
return OK;
}
实现删除操作
Status ListDelete_Sq(SqList &L, int i, ElemType &e){
if((i < 1) || (i > L.length)) return ERROR;
int *p;
int *q;
p = &(L.elem[i-1]); // p = L.elem + i -1; 地址值的不同的表示方法
e = *p; //被删除的元素赋给e
q = L.elem + L.length -1;
for(++p; p <= q; ++p) *(p-1) = *p; //
--L.length;
return OK;
}
查找第一个与e相等的值的地址
Status compare(ElemType c1,ElemType c2){
if(c1==c2)
return TRUE;
else
return FALSE;
}
int LocateElem_Sq(SqList L, ElemType e, Status(*compare)(ElemType, ElemType)){
//在顺序线性表L中查找第一个值与e满足compare()的元素的位序
//若找到,则返回其在L中的位序,否则返回0
int i = 1;
int *p;
p = L.elem;
while(i <= L.length && !(*compare)(*p++, e)) ++i;
if(i <= L.length) return i;
else return 0;
}
随便的一些示例
int main(){
SqList L;
Init_Sq(L);
L.length = 10;
int i, j, a;
for(i = 0; i<10; i++)
{
L.elem[i] = i;
}
ListInsert_Sq(L, 2, 10);
ListDelete_Sq(L, 4, a);
for(j = 0; j < L.length; j++)
{
printf("第%d个数字是%d\n", j+1 , L.elem[j]);
}
printf("\n被删除的数字是%d", a);
int k;
k = LocateElem_Sq(L, 8,compare);
printf("\n位置是%d", k);
//printf("%d %d", L.elem[1], *(L.elem + 2)); L.elem[1] == *(L.elem + 1)
//说明L.elem + 1 作为(L.elem)的下一个地址,指向的就是顺序表的下一个数 L.elem[1]
return 0;
}