-
对线性表的顺序存储结构的复习
-
一些顺序表的基本操作函数
-
顺序表是一种随机存取的储存结构
-
尽量贴近伪代码,但能运行
-
看万遍代码不如写一遍,希望大家有所启发
#include <iostream>
# define TRUE 1
#define FALSE 0
# define OK 1
# define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
//预设定义常量和类型
using namespace std;
typedef int Status;
typedef int ElemType;
//顺序表
#define List_size 100 //初始分配空间
#define LIS 10//分配增量
typedef struct {
ElemType * e;
int length;
int listsize;
}SqList;
Status InitList(SqList &L)
{
L.e = (ElemType *)malloc(List_size * sizeof(ElemType));
if (!L.e) exit(OVERFLOW);
L.length = 0;
L.listsize = List_size;
return OK;
}
Status DestroyTriplet(SqList & L)
{
free(L.e); L.e = NULL;
return OK;
}
int Listlength(SqList &L)
{
return L.length;
}
Status ListEmpty(SqList&L)
{
if (Listlength(L) == 0)
return TRUE;
else
return FALSE;
}
Status ListInsert(SqList &L, int i, ElemType e)
{
if (i<1 || i>L.length + 1) return ERROR;
if (L.length >= L.listsize) {
ElemType *NEWBASE;
NEWBASE = (ElemType*)realloc(L.e, (L.listsize + LIS) * sizeof(ElemType));
if (!NEWBASE) exit(OVERFLOW);
L.e = NEWBASE;
L.listsize += LIS;
}
ElemType *q,*p;
q = &(L.e[i - 1]);
for (p = &(L.e[L.length - 1]); p >= q; --p) *(p + 1) = *p;
*q = e;
++L.length;
return OK;
}
Status ListDelete(SqList&L, int i, ElemType &e)
{
if (i<1 || i>L.length) return ERROR;
ElemType *q, *p;
p = &(L.e[i - 1]);
e = *p;
q = L.e+ L.length - 1;
for (++p;p<=q;++p )
{
*(p - 1) = *p;
}--L.length;
return OK;
}
int LocateElem(SqList &L, ElemType e)
{
int i = 1;
while (i <= L.length)
{
if (L.e[i - 1] == e) return i;
i++;
}
return 0;
}
void mergelist(SqList la, SqList lb, SqList &lc)
{InitList(lc);
int i = 0; int j = 0; int k = 0;
for (; i <= la.length-1 &&j<=lb.length-1;)
{
if (la.e[i] <= lb.e[j]) {
ListInsert(lc,++k,la.e[i]); i++;
}
else { ListInsert(lc, ++k, lb.e[j]); j++; }
}
for (; i <= la.length-1 ; i++)
{
ListInsert(lc, ++k, la.e[i]);
}
for (; j <= lb.length -1; j++)
{
ListInsert(lc,++ k, lb.e[j]);
}
}
void display(SqList l)
{
for (int i = 1; i <= l.length; i++)
cout << l.e[i - 1] <<'\t';
cout << '\n';
}
int main()
{
SqList la, lb, lc; int n; int e; InitList(la); InitList(lb);
cout << "请你输入la的长度;\n";
cin >> n;
for (int i = 1; i <= n; i++)
{
cout << "输入" << i << "个元素\n";//注意这里未考虑乱序,必须输入一个从大到小的顺序表
cin >> e;
ListInsert(la, i, e);
}
display(la);
cout << "请你输入lb的长度;\n";
cin >> n;
for (int i = 1; i <= n; i++)
{
cout << "输入" << i << "个元素\n";
cin >> e;
ListInsert(lb, i, e);
}
display(lb);
cout << "合并为:\n";
mergelist(la, lb, lc);//lc依然从大到小排列
display(lc);
}