20190901
#include<stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
#define LIST_INCREMENT 10
//用的表是从第一位开始的,即第一位是elem[1],第0位拿来存放表的信息
typedef struct item{//定义非0项
int zhishu;
int xishu;
}Poly;
//定义线性表中的元素
typedef struct list{//定义表
Poly *elem;//定义存储空间得基地址
int length;//存储长度
int size;//当前存储空间
}SQlist;
enum status{//定义枚举类型的状态类型
OK,
FAILED,
OVERFLOW
};
status initSQlist(SQlist &list){//初始化
list.elem=(Poly *)malloc(sizeof(Poly)*MAXSIZE);//动态申请一片空间
// 需要强制转换成线性表中元素类型的指针
if(!list.elem){
return OVERFLOW;}//如果是空指针(未能成功分配到空间)
list.length=0;
list.size=MAXSIZE;
return OK;
}
status resizeSQlist(SQlist &list){//拓展
printf("Resize.....\n");
list.elem=(Poly*)realloc(list.elem, sizeof(Poly)*(MAXSIZE+LIST_INCREMENT));
//realloc函数和malloc不同的地方在于realloc是对已经有的空间进行修改
if(!list.elem){
return OVERFLOW;
}
list.size+=LIST_INCREMENT;//扩展时要把空间容量增大
}
status printSQlist(SQlist &list){//打印表
printf("Print...\n");
int i=1;
for(;i<=list.length;i++) {
printf("%d,", list.elem[i].xishu);
}
}
status insertSQlist(SQlist &list,int position,Poly item){//插入
if(position<=1||(position>list.length+1)){//插入位置不对
return FAILED;
}
if(position>=list.size){//如果插入的比存储空间大就拓展
status res =resizeSQlist(list);
if(res!=OK){
return FAILED;
}
}
Poly *p=&list.elem[position];//将地址赋值给指针变量
Poly *q=&list.elem[list.length];
for(;q!=p;q--){
*(q+1)=*q;//从position开始往后移一位
}
list.length++;
*p=item;
return OK;
}
status deleteSQlist(SQlist &list,int position){//删除
if(position<1||position>list.length+1){
return FAILED;
}
Poly *p=&list.elem[position];
Poly *q=&list.elem[list.length];
for(;p!=q;p++){
*p=*(p+1);
}
list.length--;
return OK;
}
status destorySQlist (SQlist *list) {//销毁表
if(list){//如果表存在
free(list);
list=NULL;
return OK;
}
else
return FAILED;
}