typedef int ElemType;
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define MAXSIZE 100
#define Status int
#include
typedef int ElemType;
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define MAXSIZE 100
#define Status int
typedef struct {
ElemType *elem;
int length;
}SqList;
Status InitList_Sq(SqList &L){
L.elem=new ElemType[MAXSIZE];
if(!L.elem) return(OVERFLOW);
L.length=0;
return OK;
}
Status ListInsert_Sq(SqList &L,int i ,ElemType e){
int j;
if(i<1 || i>L.length+1) return ERROR; //i值不合法
if(L.length==MAXSIZE) return ERROR; //当前存储空间已满
for(j=L.length-1;j>=i-1;j--)
L.elem[j+1]=L.elem[j]; //插入位置及之后的元素后移
L.elem[i-1]=e; //将新元素e放入第i个位置
++L.length; //表长增1
return OK;
}
void traverse(SqList L){
int i;
for(i=0;i printf("%d ",L.elem[i]); } printf("\n"); } int main(){ SqList list; InitList_Sq(list); ListInsert_Sq(list,1,5); ListInsert_Sq(list,1,7); ListInsert_Sq(list,1,3); traverse(list); printf("hello!\n"); return 0; } 头文件 线性表的上机操作代码 出现过的头文件在程序之前必须标注出来 初始化 取值 查找 插入 删除 几个基本常见操作 2. 取值(根据位置i获取相应位置数据元素的内容) 3.查找(根据指定数据获取数据所在的位置) 4.插入 ( 在线性表L中第i个数据元素之前插入数据元素e) Status ListInsert_Sq(SqList &L,int i ,ElemType e){ if(i<1 || i>L.length+1) return ERROR; //i值不合法 if(L.length==MAXSIZE) return ERROR; //当前存储空间已满 for(j=L.length-1;j>=i-1;j--) L.elem[j+1]=L.elem[j]; //插入位置及之后的元素后移 L.elem[i-1]=e; //将新元素e放入第i个位置 ++L.length; //表长增1 return OK; } 5.删除 写出一个完整程序的步骤 主函数+调用 int main(){ //初始化 SqList list; InitList_Sq(list); //调用插入 ListInsert_Sq(list,1,8); ListInsert_Sq(list,2,5); ListInsert_Sq(list,1,9); traverse(list); printf("Hello!!\n"); } 1,顺序表的类型定义 typedef struct{ ElemType *elem; //指向数据元素的基地址 int length;//线性表当前的长度 }SqList; 2,初始化线性表L Status InitList_Sq(SqList &L){ //构造一个空的顺序表L L.elem=new ElemType[MAXSIZE]; //为顺序表分配空间 if(!L.elem) return(OVERFLOW); //存储分配失败 L.length=0;//空表长度为0 return OK; } 3, 在线性表L中第i个数据元素之前插入数据元素e Status ListInsert_Sq(SqList &L,int i ,ElemType e){ int j; if(i<1 || i>L.length+1) return ERROR; //i值不合法 if(L.length==MAXSIZE) return ERROR; //当前存储空间已满 for(j=L.length-1;j>=i-1;j--) L.elem[j+1]=L.elem[j]; //插入位置及之后的元素后移 L.elem[i-1]=e; //将新元素e放入第i个位置 ++L.length; //表长增1 return OK; } 4,遍历并输出 void traverse(SqList L){ int i; for(i=0;i printf("%d ",L.elem[i]);//输出第i个元素 } printf("\n");//换行 }