1
#include
#include
#include
struct LinerList//定义线性表结构
{
//强化理解这里*list号的含义,保证L->list[i]不报错:表达式必须包含指向对象的指针类型//以及(L->list=(int*)malloc(ms*sizeof(int)))==NULL)正常分配
int *list;//存线性表元素
int size;//存线性表长度
int MAXSIZE;//存list数组元素个数
};
typedef struct LinerList LIST;
void InitLIST(LIST *L,int ms)
{ //初始化线性表
if((L->list=(int*)malloc(ms*sizeof(int)))==NULL)
{
printf("内存申请失败!\n");
exit(1);
}
L->size=0;
L->MAXSIZE=ms;
}
int InsertLIST(LIST *L,int item,int rc)
{//将item插入线性表L的rc位置
//item为记录值,rc为插入位置
int i;
if(L->size==L->MAXSIZE) //线性表已满
return -1;
if(rc<0) //插入位置为0到L->size
rc=0;
if(rc>L->size)
for(i=L->size-1;i>=rc;i--)
//L[i+1]=L[i];
L->list[i+1]=L->list[i];//线性表元素后移
L->list[rc]=item;
L->size++;
return 0;
}
void OutputLIST(LIST *L)
{//输出线性表元素
int i;
for(i=0;isize;i++)
printf("%d ",L->list[i]);
printf("\n");
}
int FindLIST(LIST *L,int item)
{//寻找线性表元素,返回≥0为元素位置,-1为没找到
int i;
for(i=0;isize;i++)
{
if(item==L->list[i])//找到相同元素,返回位置
return i;
}
return -1;
}
int DeleteLIST1(LIST *L,int item)//找到相同元素进行删除
{//删除指定元素值的线性表记录,返回≥0为删除成功
int i,n;
for(i=0;isize;i++)
if(item==L->list[i])
break;
if(isize)
{
for(n=i;nsize-1;n++)
L->list[n]=L->list[n+1];
L->size--;
return i;
}
return -1;
}
int DeleteLIST2(LIST *L,int rc)
{//删除指定rc位置的元素记录
int i;
if(rc<0||rc>=L->size)
return -1;
for(i=rc;isize-1;i++)
L->list[i]=L->list[i+1];
L->size--;
return 0;
}
void main()
{
LIST LL;
int i,r;
//printf("LIST addr=%p\tsize=%d\tMaxSize=%d\n",LL.list,LL.size,LL.MAXSIZE);
InitLIST(&LL,10);
printf("LIST addr=%p\tsize=%d\tMaxSize=%d\n",LL.list,LL.size,LL.MAXSIZE);
OutputLIST(&LL);
while(1)
{
printf("请输入元素值,输入0结束插入操作:");
fflush(stdin);
scanf("%d",&i);
if(i==0)break;
printf("请输入插入位置:");
scanf("%d&q
uot;,&r);
InsertLIST(&LL,i,r-1);
printf("线性表为: ");
OutputLIST(&LL);
}
while(1)
{
printf("请输入查找的元