|
发表于 2020-10-24 19:25:04
|
显示全部楼层
#include <stdio.h>
#include <stdlib.h>
typedef int Status;
typedef int Elemtype;
#define OK 1
#define ERROR 0
#define INIT_LIST_SIZE 100
#define LISTINCREMENT 10
typedef struct list
{
Elemtype *elem;
int length;
int listsize;
}Sqlist;
Sqlist L;
Status Initlist(Sqlist &L)
{
L.elem=(Elemtype*)malloc(INIT_LIST_SIZE*sizeof(Elemtype));
if(L.listsize==0)
return 0;
L.length=0;
L.listsize=INIT_LIST_SIZE;
return OK;
}
Status Creatlist(Sqlist &L)
{
int i,n;
printf("输入元素个数:\n");
scanf("%d",&n);
printf("\n");
printf("输入元素:\n");
for(i=0;i<n;i++)
{
scanf("%d",&L.elem[i]);
L.length++;
}
return 1;
}
Status printlist(Sqlist &L)
{
int i;
for(i=0;i<L.length;i++)
printf("%d\n",L.elem[i]);
return 1;
}
Status Insertlist(Sqlist &L,int i,Elemtype e)
{
Elemtype *q,*p,*newbase;
if(i<1||i>L.length+1)
ERROR;
if(L.length>=L.listsize)
newbase=(Elemtype*)realloc(L.elem,(L.listsize+LISTINCREMENT)*sizeof(Elemtype));
L.elem=newbase;
L.listsize+=LISTINCREMENT;
q=&(L.elem[i-1]);
for(p=&(L.elem[L.length-1]);p>=q;p--)
*(p+1)=*p;
*q=e;
L.length++;
}
Status Deletelist(Sqlist &L,int i)
{
if(i<1||i>L.length)
ERROR;
Elemtype *p,*q;
p=&(L.elem[i-1]);
q=L.elem+L.length-1;
for(++p;p<=q;++p)
*(p-1)=*p;
L.length--;
}
Status Getlist(Sqlist &S,int i)
{
if(i<1||i>L.length)
ERROR;
Elemtype *e;
e=&(L.elem[i-1]);
return *e;
}
int main()
{
int i,m,x;
Initlist(L);
printf("表:\n");
Creatlist(L);
printlist(L);
printf("\n");
printf("删除第几个元素:\n");
scanf("%d",&m);
Deletelist(L,m);
printlist(L);
printf("插入元素的位置\n:");
scanf("%d",&i);
printf("插入元素:\n");
scanf("%d",&m);
printf("\n");
Insertlist(L,i,m);
printlist(L);
printf("\n");
printf("获得元素是\n");
scanf("%d",&x);
printf("%d\n",Getlist(L,x));
return 0;
} |
|