第二章:线性表(2)
-----------------------------------------------------------------------------------------------------------------------------------
以下代码经过VC编译器:
文件名的后缀是 .cpp
#include<stdio.h>
#include<stdlib.h>
#define LIST_INIT_SIZE 10 //线性表初始长度
#define LISTINCREMENT 10 //线性表每次扩充长度
#define OK 1
#define ERROR 0
typedef int Status; //Status 是函数的类型,其值是函数结果状态代码
//线性表结构体
typedef struct{
Status *elem;
int length;
int listsize;
}SqList;
//初始化线性表
Status InitList(SqList *L){
//构造一个空的线性表 L
L->elem = (Status *)malloc(LIST_INIT_SIZE * sizeof(Status)); //构建线性表,且将线性表首地址置位 L.elem
if(!L->elem) exit(0); //分配内存失败
L->length=0; //空表长度为0
L->listsize = LIST_INIT_SIZE; //初始存储容量
return OK;
}
//向线性表中插入数据
Status ListInsert(SqList *L,int i,Status e){ //在顺序线性表L中第 i 个位置插入新的元素 e
//i的合法值为 1<= i <= ListLength_Sq(L)+1
if(i<1||i>L->length+1) return ERROR;
if(L->length >= L->listsize){ //当前存储空间已满,增加分配
//使用realloc函数,在原本的基地址上申请更大的存储空间
Status *newbase = (int *)realloc(L->elem,(LIST_INIT_SIZE + LISTINCREMENT) * sizeof(Status));
if( !newbase ) exit(0); //存储分配失败
L->elem=newbase; //新基址
L->listsize += LISTINCREMENT; //增加存储空间
}
int *q = &(L->elem[i-1]); //q为插入的位置
int *p;
for(p=&L->elem[L->length-1];p>=q;--p)
*(p+1)=*p; //插入位置及之后的元素后移
*q=e; //插入e
++L->length;
return OK;
}
//输出线性表
Status ListShow(SqList *L){
int i;
for(i=0;i<L->length;i++)
printf("%d",L->elem[i]);
printf("\n");
return OK;
}
void main(){
int i;
SqList L;
//初始化线性表
InitList(&L);
//输入数据
int n;
printf("预先输入的原始数据个数是:");
scanf("%d",&n);
printf("请输入 %d 个线性表的数据",n);
for(i=0;i<n;i++){
int t;
scanf("%d",&t);
ListInsert(&L,L.length+1,t);
}
ListShow(&L);
}