数据结构之顺序表
前言顺序表基本算法实现
前言
最近在做一些考研题目,发现有些同学不会去实现数据结构的代码,我就将李春葆老师的数据结构第5版中的算法实现了一些基础的功能给同学们参考,大家可以在此基础上实现新的功能并验证,代码可以直接运行,编译器我用的是dev C++.
顺序表基本算法实现
#include<iostream>
#include<cstdlib>
using namespace std
;
#define MaxSize 50
typedef int ElemType
;
typedef struct
{
ElemType data
[MaxSize
];
int length
;
}SqList
;
void CreateList(SqList
*&L
,ElemType a
[],int n
)
{
int i
=0,k
=0;
L
=(SqList
*)malloc(sizeof(SqList
));
while(i
<n
)
{
L
->data
[i
]=a
[i
];
k
++;
i
++;
}
L
->length
=k
;
}
void InitList(SqList
*&L
)
{
L
=(SqList
*)malloc(sizeof(SqList
));
L
->length
=0;
}
void DestroyList(SqList
*&L
)
{
free(L
);
}
bool ListEmpty(SqList
*L
)
{
return (L
->length
==0);
}
int ListLength(SqList
*L
)
{
return L
->length
;
}
void DispList(SqList
*L
)
{
for(int i
=0;i
<L
->length
;i
++)
{
printf("%d ",L
->data
[i
]);
}
printf("\n");
}
bool GetElem(SqList
*L
,int i
,ElemType
&e
)
{
if(i
<1||i
>L
->length
) return false;
e
=L
->data
[i
-1];
return true;
}
int LocateElem(SqList
*L
,ElemType e
)
{
int i
=0;
while(i
<L
->length
&&L
->data
[i
]!=e
) i
++;
if(i
>=L
->length
) return false;
else return i
+1;
}
bool ListInsert(SqList
*&L
,int i
,ElemType e
)
{
int j
;
if(i
<1||i
>L
->length
+1) return false;
i
--;
for(j
=L
->length
;j
>i
;j
--)
{
L
->data
[j
]=L
->data
[j
-1];
}
L
->data
[i
]=e
;
L
->length
++;
return true;
}
bool ListDelete(SqList
*&L
,int i
,ElemType
&e
)
{
int j
;
if(i
<1||i
>L
->length
) return false;
i
--;
e
=L
->data
[i
];
for(j
=i
;j
<L
->length
;j
++)
{
L
->data
[j
]=L
->data
[j
+1];
}
L
->length
--;
return true;
}
int main()
{
SqList
*L
;
ElemType e
;
int a
[]={1,2,3,4,5};
InitList(L
);
CreateList(L
,a
,5);
DispList(L
);
ListEmpty(L
)==0?cout
<<"not null"<<endl
:cout
<<"null"<<endl
;
cout
<<ListLength(L
)<<endl
;
GetElem(L
,3,e
);
cout
<<e
<<endl
;
cout
<<LocateElem(L
,3)<<endl
;
ListInsert(L
,6,6);
DispList(L
);
ListDelete(L
,3,e
);
DispList(L
);
DestroyList(L
);
return 0;
}
转载请注明原文地址:https://tech.qufami.com/read-15212.html