线性表
线性表是一种应用范围十分广泛的抽象化的数据结构,是由零个或多个具有相同类型的元素组成的一个有序序列。
线性表的数组实现
#include <iostream.h>
#define maxlength 100
struct LIST{
Elementtype elements[maxlength];/*用来存放表中元素的数组*/
int last;/*用来指示表中的最后一个元素在数组的位置*/
};
typedef int position;
position End(LIST L)
{
return (L.last + 1);
}/*查询线性表的元素个数*/
void Insert(Elementtype x,position p,LIST &L)
/*Insert 把x插入到表L中的位置P处*/
{
position q;
if(L.last >= maxlength - 1)
error("list is full");
else if((p > L.last+1)||(p < 1))
error("position does not exist");
else{
for(q = L.last;q >= P;q--)
/*将位置p、p+1...的元素向下移动一个位置*/
L.elements[q+1] = L.elements[q];
L.last = L.Last + 1;
L.elements[p] = x;
}
}/*插入*/
void Delete(position p,LIST &L)
/*Delete删除L中位置p中的位置*/
{
position q;
if((p > L.last)||(p < 1))
error("position does not exist");
else{
L.last = L.last - 1;
for(q = p;q <= L.last;q++){
/*将位置为p,p+1,...的元素向上移动一个位置*/
L.elements[q] = L.elements[q+1];
}
}/*删除*/
position Locate(Elementtype x,LIST L)
/*Locate返回表L中元素x的位置*/
{
position q;
for(q = 1;q <= L.last;q++)
if(L.elements[q] == x)
return q;
return(L.last+1);/*若x不存在*/
}/*查询*/