#include<stdio.h>
#include<stdlib.h>
struct LinearList
{
int *list;
int size;
int MaxSize;
};
typedef struct LinearList 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)
{
int i;
if(L->size>=L->MaxSize)
return -1;
if(rc<0)
rc=0;
if(rc>L->size)
rc=L->size;
for(i=L->size-1;i>=rc;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;i<L->size;i++)
printf("%d",L->list[i]);
printf("\n");
}
int FindList(LIST *L,int item)
{
int i;
for(i=0;i<L->size;i++)
if(item==L->list[i]);
return i;
return -1;
}
int DeleteList(LIST *L,int item)
{
int i,n;
for(i=0;i<L->size;i++)
if(item==L->list[i])
break;
if(i<L->size)
{
for(n=i;n<L->size-1;n++)
L->list[n]=L->list[n+1];
L->size--;
return i;
}
return -1;
}
int DeleteList2(LIST *L,int rc)
{
int i,n;
if(rc<0||rc>=L->size)
return 1;
for(n=rc;n<L->size-1;n++)
L->list[n]=L->list[n+1];
L->size--;
return 0;
}
int main()
{
LIST LL;
int i,r;
printf("没有初始化情况:list addr=%p\tsize=%d\tMaxSize=%d\n",LL.list,LL.size,LL.MaxSize);
InitList(&LL,100);
printf("初始化后的情况:list addr=%p\tsize=%d\tMaxSize=%d\n",LL.list,LL.size,LL.MaxSize);
while(1)
{
printf("请输入元素值,输入0结束插入操作:");
fflush(stdin); /*清空标准输入缓冲区*/
scanf("%d",&i);
if(i==0)
break;
printf("请输入插入位置:");
scanf("%d",&r);
InsertList(&LL,i,r-1);
printf("线性表为: ");
OutputList(&LL);
}
while (1)
{
printf("请输入查找元素值,输入0结束查找操作");
fflush(stdin); //清空标准输入缓冲区
scanf("%d",&i);
if(i==0)
break;
r=FindList(&LL,i);
if(r<0)
printf("没找到\n");
else
printf("有符合条件的元素,位置为: %d\n",r+1);
}
while(1)
{
printf("请输入查找元素值,输入0结束查找操作");
fflush(stdin); //清空标准输入缓冲区
scanf("%d",&i);
if(i==0)
break;
r=DeleteList(&LL,i);
if(r<0)
printf("没找到\n");
else
printf("有符合条件的元素,位置为: %d\n",r+1);
OutputList(&LL);
}
while(1)
{
printf("请输入查找元素值,输入0结束查找操作");
fflush(stdin); //清空标准输入缓冲区
scanf("%d",&i);
if(i==0)
break;
r=DeleteList||(&LL,r-1);
if(r<0)
printf("位置越界\n");
else
{
printf("线性表为:");
OutputList(&LL);
}
}
}
数据结构课后习题答案_基础题1
猜你喜欢
转载自blog.csdn.net/qq_41709044/article/details/83316708
今日推荐
周排行