#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define ERROR -1
#define MAX_SIZE 100
typedef int Status;
typedef int ElemType;
typedef struct sqlist
{
ElemType Elem_array[MAX_SIZE];
int length;
}Sqlist;
//插入运算
Status InsertElem(Sqlist *L,int i,ElemType e)
{
int j;
if(i<0||i>L->length + 1)
return ERROR;
if(L->length>MAX_SIZE)
{
printf("线性表溢出!\n");
}
for(j = L->length-1;j>=i-1;j--)
{
L->Elem_array[j+1] = L->Elem_array[j];
}
L->Elem_array[i-1] = e;
L->length++;
return OK;
}
void PrintList(Sqlist *L)
{
int i;
for(i = 0;i<L->length;i++)
{
printf("%d\n",L->Elem_array[i]);
}
}
Status CreatList(Sqlist *L)
{
int len;
int i;
//ElemType q;
printf("请输入想要创建表的长度:");
scanf("%d",&len);
if(len<0||len>MAX_SIZE)
return ERROR;
L->length = len;
for(i = 0;i<len;i++)
{
scanf("%d",&L->Elem_array[i]);
}
}
//删除第i个元素
Status Delete(Sqlist *L,int i)
{
int j;
ElemType x;
if(L->length==0)
{
printf("表为空!\n");
return ERROR;
}
else if(i<0||i>L->length + 1)
{
printf("要删除的元素不存在!");
return ERROR;
}
else
{
x=L->Elem_array[i-1];
for(j=i;j<L->length;j++)
{
L->Elem_array[j-1] = L->Elem_array[j];
}
L->length--;
return(x);
}
}
//查找定位删除操作
Status Locate_Delete(Sqlist *L,ElemType x)
{
int i;
int j;
if(L->length==0)
{
printf("表为空!\n");
return ERROR;
}
for(i = 0;i<L->length;i++)
{
if(L->Elem_array[i]==x)
{
break;
}
}
if(i<L->length)
{
for(j = i;j<L->length;j++)
{
L->Elem_array[j] = L->Elem_array[j+1];
}
L->length--;
}
else if(i>L->length)
{
printf("要删除的元素不存在!\n");
return ERROR;
}
}
void main()
{
Sqlist l;
l.length = 0;
//int l->Elem_array[MAX_SIZE];
//InsertElem(&l,1,2);
//InsertElem(&l,2,2);
//InsertElem(&l,3,2);
CreatList(&l);
printf("线性表的值如下:\n");
PrintList(&l);
InsertElem(&l,3,2);
printf("插入数值后的线性表如下:\n");
PrintList(&l);
Delete(&l,1);
printf("删除数值后的线性表如下:\n");
PrintList(&l);
Locate_Delete(&l,2);
printf("定位删除数值后的线性表如下:\n");
PrintList(&l);
}
线性表的删除及查找定位删除(完整程序)
最新推荐文章于 2022-12-09 23:11:58 发布