线性表的顺序存储结构 ——动态分配内存

  1. 对线性表的顺序存储结构的复习

  2. 一些顺序表的基本操作函数

  3. 顺序表是一种随机存取的储存结构

  4. 尽量贴近伪代码,但能运行

  5. 看万遍代码不如写一遍,希望大家有所启发

#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);

}
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值