#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 100
typedef struct List
{
int data[MAXSIZE];
int length;
} List;
//初始化
void InitList(List *L)
{
L->length = 0;
return ;
}
//清空
void ClearList(List *L)
{
L->length = 0;
return ;
}
//插入
//插入时下标是从0~length-1,而不是1~length
void InsertList(List *L,int p,int e)
{
if(L->length-1 == MAXSIZE)
{
printf("The List is full.\n");
return ;
}
if(p<0 || p>L->length)
{
printf("Please input a new position.\n");
return ;
}
//如果插入位置p刚好在原List最后一个元素的后面
//则不需要进行for循环
if(p<=L->length-1)
for(int i = L->length-1; i>=p; i--)
{
L->data[i+1] = L->data[i];
}
L->data[p] = e;
L->length++;
return;
}
//删除
void DeleteList(List *L,int p,int *e)
{
if(p<0 || p>L->length-1)
{
printf("Please input a new position.\n");
return ;
}
*e = L->data[p];
for(int i=p; i<L->length-1; i++)
L->data[i] = L->data[i+1];
L->length--;
}
//打印
void PrintList(List L)
{
if(L.length == 0)
{
printf("The List is empty.\n");
return ;
}
for(int i=0; i<L.length; i++)
printf("%d ",L.data[i]);
printf("\n\n");
}
int main()
{
List L;
InitList(&L);
printf("L.length == %d\n",L.length);
InsertList(&L,0,12);
InsertList(&L,0,23);
InsertList(&L,1,78);
InsertList(&L,3,99);
printf("After Insert.\nPrint the List: ");
printf("L.length == %d\n",L.length);
PrintList(L);
int e = 0;
DeleteList(&L,0,&e);
printf("e = %d\n",e);
DeleteList(&L,2,&e);
printf("e = %d\n",e);
printf("After Delete.\nPrint the List: ");
printf("L.length == %d\n",L.length);
PrintList(L);
ClearList(&L);
printf("After Clear.\nPrint the List: ");
printf("L.length == %d\n",L.length);
PrintList(L);
return 0;
}