编程练习:table
/***************************************************************************************新手每日一练:线性表
****************************************************************************************/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct{
int data[100];
int length;
}List;
void CreatList(List *L,int *a,int n);
void InitList(List **L);
void DstroyList(List *L);
int ListEmpty(List *L);
int ListLength(List *L);
void DisplayList(List *L);
int GetElem(List *L,int i,int *e);
int ListInsert(List *L,int i,int e);
int ListDelete(List *L,int i,int *e);
int main(void)
{
List *L;
int a[6] = {2,1,5,7,4,8};
int Insert_Index,Delete_Index,Delete_Elem;
int List_Length = 0,Elem = 0;
InitList(&L);
CreatList(L,a,6);
DisplayList(L);
printf("\n-------------\n");
List_Length = ListLength(L);
printf("List_Length == %d\n",List_Length);
GetElem(L,3,&Elem);
printf("the 3 Elem is %d\n",Elem);
printf("\n-------------\n");
printf("please input the Insert_Index:");
scanf("%d",&Insert_Index);
ListInsert(L,Insert_Index,11);
DisplayList(L);
printf("\n-------------\n");
printf("please input the Delete_Index:");
scanf("%d",&Delete_Index);
ListDelete(L,Delete_Index,&Delete_Elem);
DisplayList(L);
printf("the Delete_Elem is %d\n",Delete_Elem);
printf("\n-------------\n");
DstroyList(L);
return 0;
}
void CreatList(List *L,int *a,int n)
{
int i;
for(i = 0;i < n;i++)
L->data[i] = a[i];
L->length = n;
}
void InitList(List **L)
{
*L = (List *)malloc(sizeof(List));
}
void DstroyList(List *L)
{
free(L);;
}
int ListEmpty(List *L)
{
return ( 0 == L->length);
}
int ListLength(List *L)
{
return (L->length);
}
void DisplayList(List *L)
{
int i;
if(ListEmpty(L))
return 1;
for(i = 0;i < L->length;i++)
printf("%d ",L->data[i]);
}
int GetElem(List *L,int i,int *e)
{
if(i < 0 || i > L->length + 1)
return 1;
*e = L->data[i - 1];
return 0;
}
int ListInsert(List *L,int i,int e)
{
int j;
if(i < 0 || i > L->length + 1)
return 1;
i = i - 1;
for(j = L->length;j > i;j--)
L->data[j] = L->data[j - 1];
L->data[j] = e;
L->length += 1;
return 0;
}
int ListDelete(List *L,int i,int *e)
{
int j;
if(i < 0 || i > L->length)
return 1;
i = i - 1;
*e = L->data[i];
for(j = i;j < L->length;j++)
{
L->data[j] = L->data[j + 1];
}
L->length -= 1;
return 0;
}