#include<stdio.h>
#define MaxSize 20
#define true 1
#define false -1
typedef struct
{
int elem[MaxSize];
int length;
}SL;
/*线性表初始化:无元素*/
void SL_Init(SL * L)
{
L->length=0;
}
/*线性表判空*/
int Is_Empty(SL *L)
{
if(L->length==0)
{
printf("SL is empty\n");
return false;
}
else return true;
}
/*创造线性表*/
void SL_Create(SL *L,int a[],int n)
{
int i;
if(L->length==0)
{ for(i=0;i<n;i++)
{
L->elem[i]=a[i];
}
L->length=n;
}
}
/*线性表第a个位置插入元素x*/
void SL_Insert(SL*L,int a,int x)
{
int i;
if( (a<1)||(a > ( L->length+1)) )
{ printf("this position cannot be chosen\n");
return ;
}
if(L->length>=MaxSize)
return ;
for(i=L->length;i>=a;i--)
{ L->elem[i]=L->elem[i-1];
}
L->elem[a-1]=x;
L->length++;
}
/*删除线性表位置a的元素*/
void SL_Delete(SL*L,int a)
{
int i;
if( (a<1) ||(a>L->length) )
{
printf("this position no num\n");
return ;
}
for(i=a;i<L->length;i++)
{
L->elem[i-1]=L->elem[i];
}
L->length--;
}
/*查找某数x,输出其位置*/
int SL_find(SL*L,int x)
{
int i;
for(i=0;i<L->length;i++)
{
if(L->elem[i]==x)
break;
}
if(i<=L->length)
{ return i+1;}
return false;
}
/*定位a位置元素的值*/
void SL_locate(SL*L,int a,int *p)
{
if ( (a<0)||(a>=L->length) )
{ printf("bad position\n");
return ;}
*p=L->elem[a-1];
}
/*输出线性表*/
void SL_print(SL*L)
{
int j;
while(L->length==0);
for(j=0;j<L->length;j++)
{
printf("%4d",L->elem[j]);
}
}
/*销毁线性表*/
void SL_Destory(SL*L)
{
if(!L->elem) //没有可销毁的内容
return ;
free(L->elem);
L->length =0;
}
int main()
{
SL *L1;
SL L2;
int j,num;
int x=-2;
int z;
L1=&L2;
SL_Init(L1);
for(j=0;j<6;j++)
{
printf("Enter %d num:\n",j+1);
scanf("%d",&num);
SL_Insert(L1,j+1,num);
}
SL_print(L1);
printf("\n");
SL_Insert(L1,2,10);
printf("插入一个数后:\n");
SL_print(L1);
SL_Delete(L1,2);
printf("删除一个数后:\n");
SL_print(L1);
z=SL_find(L1,4);
printf("\nfind result:%d\n",z);
SL_locate(L1,4,&x);
printf("locate result is %d\n",x);
return 0;
}