线性表的简单实现
1,增
2,删
3,改
4,查
5,插入
#include<stdio.h>
#include<stdlib.h>
#include<windows.h>
#define OK 1
#define ERROR 0
#define LIST_INIT_SIZE 100//线性表存储空间的初始分配量
#define LISTINCREMENT 10//线性表存储空间分配增量
#define N 10//初始插入数据量
typedef int Status;
typedef int Elemtype;
typedef struct SqList{
Elemtype* elem;
Elemtype length;
Elemtype listsize;
}SqList;
Status InitList_Sq(SqList &L){
//构造一个线性空表
L.elem=(Elemtype *)malloc(LIST_INIT_SIZE*sizeof(Elemtype));
if(!L.elem){
printf("ERROR\n");
exit(ERROR);
}
L.length=0;
L.listsize=LIST_INIT_SIZE;
printf("SUCCESSFULLY\n");
return OK;
}
Status getSqList(SqList &L,Elemtype e){
if(L.length*4<L.listsize){
L.elem=&e;
printf("%d\t",*L.elem);
L.length++;
Sleep(500);
printf("Over!\n");
}
else{
printf("长度超限!\n");
exit(ERROR);
}
}
Status ListInsert_Sq(SqList &L,Elemtype i,Elemtype e){//线性表首地址,插入位置,插入元素
//在顺序线性表L中第i个位置之前插入新的元素
//判断i的位置是否合法
if(i<1 || i>L.length){
printf("i的位置不合法!\n");
exit(ERROR);
}
if(L.length>=L.listsize){
printf("存储已满,重新分配\n");
Elemtype *newbase=(Elemtype *)realloc(L.elem,(L.listsize+LISTINCREMENT)*sizeof(Elemtype));
if(!newbase){
printf("重新分配失败\n");
exit(0);
}
L.elem=newbase;//新地址
L.listsize+=LISTINCREMENT;//新增加存储量
}
Elemtype *q=&(L.elem[i-1]);//q为插入位置
for(Elemtype *p=&(L.elem[L.length-1]);p>=q;p--){
*(p+1)=*q;
}
*q=e;
L.length++;
printf("OVER!\n");
return OK;
}
Status showList(SqList L){
for(int i=0;i<L.length;i++){
printf("%d\t",L.elem[i]);
}
Sleep(500);
printf("\nOver\n");
}
int main(){
struct SqList L;//L为指针类型
InitList_Sq(L);
for(int i=0;i<N;i++){
getSqList(L,i);
}
printf("L.length:%d\n",L.length);
// ListInsert_Sq(L,1,10);
showList(L);
return 0;
}