线性表
来源:互联网 发布:PHP api创建窗口 编辑:程序博客网 时间:2024/05/17 07:46
代码:
#include<stdio.h>
#include<stdlib.h>
#define MaxSize 1000
typedef struct
{
int *elem;
int Length;
}SqList;
int InitList(SqList *L)
{
L->elem=(int *)malloc(sizeof(int)*MaxSize);
if(!L->elem)
return 0;
L->Length=0;
return 1;
}
void DestoryList(SqList *L)
{
free(L->elem);
L->Length=0;
}
void ClearList(SqList *L)
{
L->Length=0;
}
int ListLength(SqList L)
{
return L.Length;
}
int IsEmpty(SqList L)
{
if(L.Length==0)
return 1;
return 0;
}
void GetElem(SqList L,int i,int *e)
{
if(i<1||i>L.Length)
return;
e=(int *)malloc(sizeof(int));
*e=L.elem[i-1];
return;
}
int LocateELem(SqList L,int e)
{
int i;
for(i=0;i<L.Length;i++)
if(L.elem[i]==e)
return i;
return -1;
}
int ModifyElem(SqList *L,int i,int e)
{
if(i<1||i>L->Length)
return 0;
L->elem[i-1]=e;
return 1;
}
void OutputElems(SqList L)
{
int i;
for(i=0;i<L.Length-1;i++)
printf("%d ",L.elem[i]);
printf("%d\n",L.elem[L.Length-1]);
}
int ListInsert(SqList *L,int i,int e)
{
int j;
if(i<1)
return 0;
if(i>L->Length)
i=L->Length+1;
for(j=L->Length;j>=i;j--)
L->elem[j]=L->elem[j-1];
L->elem[i-1]=e;
L->Length++;
return 1;
}
int ListDelete(SqList *L,int i)
{
int j;
if(i<1||i>L->Length)
return 0;
for(j=i-1;j<=L->Length-2;j++)
L->elem[j]=L->elem[j+1];
L->Length--;
return 1;
}
int main()
{
SqList L;
InitList(&L);
ListInsert(&L,1,1);
ListInsert(&L,3,2);
ListInsert(&L,3,3);
ListInsert(&L,4,4);
ListInsert(&L,2,7);
OutputElems(L);
ListDelete(&L,2);
OutputElems(L);
return 0;
}