顺序表
存储结构
#define LIST_INIT_SIZE 20
typedef int ElemType;
typedef struct Sqlist
{
ElemType* elem;
int length;
int listsize;
}Sqlist;
建表
void InitList(Sqlist& L, int maxsize)
{
ElemType a;
int i = 0;
if (maxsize == 0) maxsize = LIST_INIT_SIZE;
L.elem = (ElemType*)malloc(maxsize * sizeof(ElemType));
if (!L.elem) exit(1);
while (1)
{
scanf("%d", &a);
if (a != -1) L.elem[i++] = a;
else break;
}
L.length = i;
L.listsize = maxsize;
}
查找
int LocateElem(Sqlist L, ElemType X)
{
int i = 0;
while (i <= L.length && L.elem[i] != X) i++;
if (i > L.length) return -1;
else return i + 1;
}
插入
bool Insert(List L, ElementType X, Position P)
{
Position i;
if (L->Last == MAXSIZE - 1) {
printf("表满");
return false;
}
if (P<0 || P>L->Last + 1) {
printf("位置不合法");
return false;
}
for (i = L->Last; i >= P; i--)
L->Data[i + 1] = L->Data[i];
L->Data[P] = X;
L->Last++;
return true;
}
顺序表删除
bool Delete(List L, Position P)
{
Position i;
if (P<0 || P>L->Last) {
printf("位置%d不存在元素", P);
return false;
}
for (i = P + 1; i <= L->Last; i++)
L->Data[i - 1] = L->Data[i];
L->Last--;
return true;
}
顺序表反转
void Reverse(Sqlist& L)
{
for (int i = 0; i < L.length / 2; i++)
{
ElemType temp = L.elem[i];
L.elem[i] = L.elem[L.length - i - 1];
L.elem[L.length - i - 1] = temp;
}
}
单链表