//线性表的基本操作
#include<stdio.h>
#include<stdlib.h>
#define InitSize 50
#define MaxSize 100
typedef int ElemType;
/*静态分配数组
typedef struct{
ElemType data[MaxSize];
int length;
}SqList;*/
//动态分配数组
typedef struct{
ElemType *data; //表示动态分配数组的指针
int length;
}SeqList;
//插入操作
bool ListInsert(SeqList &L,int i,ElemType e)
{
if(i<1 || i>L.length+1)
return false;
if(L.length>= MaxSize)
return false;
for(int j=L.length;j>=i;--j)
L.data[j] = L.data[j-1];
L.data[i-1] = e;
++L.length;
return true;
}
//删除操作
bool ListDelete(SeqList &L,int i,ElemType &e)
{
if(i<1 || i>L.length)
return false;
e = L.data[i-1];
for(int j=i;j<L.length;++j)
L.data[j-1] = L.data[j];
--L.length;
return true;
}
//按值查找
int LocateElem(SeqList L,ElemType e)
{
for(int i=0;i<L.length;++i)
if(L.data[i] == e)
return i+1;
return 0; //查找失败
}
bool printList(SeqList L)
{
for(int i=0;i<L.length;++i)
printf("%d ",L.data[i]);
printf("\n");
return true;
}
void main()
{
SeqList L;
int delVal;
L.data=(ElemType*)malloc(sizeof(ElemType)*InitSize);
L.length = 0;
int a[5]={1,3,4,5,6};
for(int i=0;i<5;++i)
{
L.data[i] = a[i];
++L.length;
}
if(ListInsert(L,2,2))
printList(L);
else
printf("ERROR INSERT!\n");
if(ListDelete(L,3,delVal))
printList(L);
else
printf("ERROR INSERT!\n");
printf("查找4所在位置:%d\n",LocateElem(L,4));
}
顺序表基本操作
最新推荐文章于 2024-06-13 23:56:26 发布