/*
//只能使用一次该结构体模块
struct
{
char title[MAXTITL];
char author[MAXAUTL];
}library;
=================================================================================
//定义一个结构体变量
struct book
{
char title[MAXTITL];
char author[MAXAUTL];
}library;
==================================================================================
//定义一个结构体数组
struct book
{
char title[MAXTITL];
char author[MAXAUTL];
}library[1000];
==================================================================================
//typedef用法
typedef struct book
{
int a;
char b;
double c;
}BK;
//使用BK类型定义变量t1、t2、t3
BK t1, t2[20], *t3;
=====================================================================================
*/
//==============================================初始化单链表===============================================
List MakeEmpty()
{
List L=(List)malloc(sizeof(struct LNode));
L->Last=-1;
return L;
}
//===================================返回线性表中X的位置。若找不到则返回ERROR;=================================
//注意次数LIST指针,即:L指针,不是结构体
//所以使用L->Data[i],而不是L.Data[i];
Position Find( List L, ElementType X )
{
int i;
for(i = 0; i <= L->Last; i++)//[0,Last]
{
if(X==L->Data[i])
{//遍历搜索查找
return i;
}
}
return ERROR;
}
//===========================将X插入在位置P并返回true。若空间已满,则打印“FULL”并返回false;======================
//============================如果参数P指向非法位置,则打印“ILLEGAL POSITION”并返回false;=======================
bool Insert( List L, ElementType X, Position P )
{
if(L->Last==MAXSIZE-1)
{//容量满
printf("FULL");
return false;
}
if(P<0||P>L->Last+1)
{//只能查到已有数字的位置或最后一个的下一个
printf("ILLEGAL POSITION");
return false;
}
int i;
for(i = L->Last+1; i > P; i--)//Last+1 ,p+1
{
L->Data[i] = L->Data[i-1];//向右平移,Data[p+1]=Data[p],循环到p+1停止
}
L->Data[i] = X;//插入
L->Last++;//个数增加
return true;
}
//==============================将位置P的元素删除并返回true。若参数P指向非法位置,==============================
//=============================则打印“POSITION P EMPTY”(其中P是参数值)并返回false。==========================
bool Delete( List L, Position P )
{
int i;
//if(L->Last==-1)return false;//为空!!!因为这一句多此一举的判断导致为空时应输出empty没输出
if(P<0||P>L->Last)
{//删除的位置不在已有位置内
printf("POSITION %d EMPTY",P);
return false;
}
for(i = P; i < L->Last; i++)//p ,last-1
{//删除后向左平移
L->Data[i] = L->Data[i+1];
}
L->Last--;//减少一个
return true;
}
6-2 顺序表操作集
最新推荐文章于 2022-12-05 20:54:57 发布