#include<stdio.h>
#include<stdlib.h>
#define ERROR 0
#define OVERFLOW -2
#define LIST_INIT_SIZE 5
#define LISTINREMENT 2
#define OK 1
typedef int Status;
typedef int ElemType;
typedef struct
{
ElemType *elem;
int length;
int listsize;
} SqList;
Status InitList_Sq(SqList &L)
{
L.elem=(ElemType *)malloc(LIST_INIT_SIZE*sizeof(ElemType));
if(!L.elem)
exit(OVERFLOW);
L.length=0;
L.listsize=LIST_INIT_SIZE;
return OK;
}
Status ListInsert_Sq(SqList &L,int i,ElemType e)
{
ElemType *newbase,*p,*q;
if(i<1||i>L.length+1)
return ERROR;
if(L.length>=L.listsize)
{
newbase=(ElemType *)realloc(L.elem,(L.listsize+LISTINREMENT)*sizeof(ElemType));
if(!newbase)
exit(OVERFLOW);
L.elem=newbase;
L.listsize+=LISTINREMENT;
}
q=&(L.elem[i-1]);
for(p=&(L.elem[L.length-1]); p>=q; p--)
*(p+1)=*p;
*q=e;
++L.length;
return OK;
}
Status ListDelete_Sq(SqList &L,int i,ElemType &e)
{
ElemType *p,*q;
if((i<1)||(i>L.length))
return ERROR;
p=&(L.elem[i-1]);
e=*p;
q=L.elem+L.length-1;
for(p++; p<=q; p++)
*(p-1)=*p;
L.length--;
return OK;
}
int main()
{
SqList L;
InitList_Sq(L);
int i;
for(i=0; i<L.listsize; i++)
{
scanf("%d",L.elem+i);
L.length++;
}
for(i=0; i<L.length; i++)
printf("%d ",*(L.elem+i));
printf("\n");
ElemType e;
scanf("%d%d",&i,&e);
ListInsert_Sq(L,i,e);
for(i=0; i<L.length; i++)
printf("%d ",*(L.elem+i));
printf("\n");
scanf("%d",&i);
ListDelete_Sq(L,i,e);
for(i=0; i<L.length; i++)
printf("%d ",*(L.elem+i));
printf("\n");
printf("e=%d\n",e);
return 0;
}
线性表的顺序表示和实现(数据结构)
最新推荐文章于 2024-04-27 23:46:01 发布