/* 线性表实现插入和删除 */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #define LIST_INIT_SIZE 100 #define LISTINCRMENT 10 #define ElemType int typedef struct{ ElemType *elem; int length; int listsize; }SqList; bool InitList_Sq(SqList &L){ //构造一个空的线性表L L.elem = (ElemType *)malloc(LIST_INIT_SIZE*sizeof(ElemType)); if(!L.elem) exit(OVERFLOW); L.length = 0; L.listsize = LIST_INIT_SIZE; return true; } //InitLst_Sq bool ListInsert_Sq(SqList &L,int i,ElemType e){ //在顺序线性表L中第i个位置之前插入新的元素 //i的合法值为1 <= i <= ListLength_Sq(L)+1 ElemType *newbase,*q,*p; if(i < 1||i > L.length + 1) //i不合法 return false; if(L.length >= L.listsize){ //当前存储空间已满,添加分配 newbase = (ElemType *)realloc(L.elem, (L.listsize+LISTINCRMENT)*sizeof(ElemType)); if(!newbase) //存储分配失败 exit(OVERFLOW); L.elem = newbase; //新地址 L.listsize += LISTINCRMENT; //添加存储容量 } q = &(L.elem[i-1]); //q为插入位置 for(p = &(L.elem[L.length-1]);p >= q;--p) *(p+1) = *p; *q = e; //插入e ++L.length; //表长加一 return true; } //ListInsert_Sq bool ListDelete_Sq(SqList &L,int i,ElemType &e) { //在顺序线性表L中删除第i个元素。并用e返回其值 ElemType *p,*q; if((i < 1)||(i > L.length)) return false; p = &(L.elem[i-1]); e = *p; q = L.elem + L.length - 1; for(++p;p <= q;++p) *(p-1) = *p; --L.length; return true; }//ListDelete_Sq int main() { int i; SqList L; puts("Please input 5 num:"); if(InitList_Sq(L)){ //创建新表。输入五个元素 for(i = 0;i < 5;i++){ scanf("%d",&L.elem[i]); ++L.length; } for(i = 0;i < 5;i++){ printf("%d ",L.elem[i]); } puts(""); } else{ puts("ERROR"); exit(OVERFLOW); } //插入元素,要插入的位置和元素值 puts("Please Input You Insert num ans possition:"); int pos,num; scanf("%d%d",&num,&pos); if(ListInsert_Sq(L,pos,num)){ printf("Insert After: "); for(i = 0;i < L.length;++i) printf("%d ",L.elem[i]); printf(" "); } else{ puts("Delete Error"); exit(OVERFLOW); } //删除元素。要删除元素的位置 puts("Please Input You want to Delete possition:"); scanf("%d",&pos); if(ListDelete_Sq(L,pos,num)){ printf("Delete After: "); for(i = 0;i < L.length;++i) printf("%d ",L.elem[i]); puts(""); } else puts("Delete Error"); return 0; }