编程语言
首页 > 编程语言> > 数据结构C++实现——线性表之顺序表(动态分配)

数据结构C++实现——线性表之顺序表(动态分配)

作者:互联网

 

线性表分为顺序表与链表

其中顺序表用存储位置的相邻来体现数据元素之间的逻辑关系,可以以静态分配或者动态分配方式实现

其基本操作有插入、删除、按位查找、按值查找等

/*
顺序表:用顺序存储的方式实现的线性表
逻辑结构:线性表
物理结构:顺序表-动态分配
*/
#include<cstdio>
#include<cstdlib>
#include<iostream>

using namespace std;

#define ElemType int
#define InitSize 10

typedef struct {
	ElemType* data;
	int MaxSize;
	int length;
}SeqList;

void InitList(SeqList& L) {                                          //初始化——对L中的三项进行设置
	L.data = (ElemType*)malloc(InitSize * sizeof(ElemType));
	L.length = 0;
	L.MaxSize = InitSize;
}

void IncreaseSize(SeqList& L, int len) {                             //增加顺序表长度
	ElemType* p = L.data;         //用p记下L.data指向的区域,以便最后释放(free)这块区域,因为原指针(L.data)马上就要变了
	L.data = (ElemType*)malloc((InitSize + len) * sizeof(ElemType));
	for (int i = 0; i < L.length; i++)
		L.data[i] = p[i];
	L.MaxSize += len;
	free(p);
}

//顺序表建立
void BuildList(SeqList& L) {
	int count = 0;
	ElemType e;

	cout << "请为顺序表指定初始情况,元素之间回车间隔,999结束:\n";
	cin >> e;
	while (e != 999) {
		L.data[L.length] = e;
		L.length++;
		cin >> e;
	}
}

//打印顺序表
void PrintList(SeqList L) {
	for (int i = 0; i < L.length; i++) {
		cout << L.data[i];
		cout << "  ";
	}
	cout << "\n";
}


//插入
bool ListInsert(SeqList& L, int i, ElemType e) {   //i是位序(1~n)
	if (i<1 || i>L.length + 1) return false;
	if (L.length >= L.MaxSize) return false;

	for (int j = L.length; j >= i; j--)             //j是数组下标
		L.data[j] = L.data[j - 1];
	L.data[i - 1] = e;
	L.length++;

	return true;
}

//删除
bool ListDelete(SeqList& L, int i, ElemType& e) {
	if (i<1 || i>L.length + 1) return false;

	e = L.data[i - 1];
	for (int j = i; j < L.length; j++)
		L.data[j - 1] = L.data[j];
	L.length--;
	return true;
}

//按位查找
ElemType GetElem(SeqList L, int i) {
	return L.data[i - 1];
}

//按值查找
int LocateElem(SeqList L, ElemType e) {
	for (int i = 0; i < L.length; i++)
		if (L.data[i] == e)
			return i + 1;
	return 0;
}
//更完备按值查找
void LocateElem2(SeqList L, ElemType e, int ee[]) {
	int ii = 1;
	for (int i = 0; i < L.length; i++)
		if (L.data[i] == e)
			ee[ii++] = i + 1;
}

//判断操作
void Judge(string s, bool b) {
	if (b) {
		cout << s;
		cout << "操作成功\n";
	}
	else {
		cout << s;
		cout << "操作失败\n";
	}
}

int main() {
	SeqList L;
	InitList(L);
	IncreaseSize(L,10);

	BuildList(L);
	cout << "输出初始化后的动态分配顺序表:\n";
	PrintList(L);
	Judge("Insert1", ListInsert(L, 3, 6));
	Judge("Insert2", ListInsert(L, 4, 9));
	cout << "输出插入后的动态分配顺序表:\n";
	PrintList(L);
	ElemType e1;
	Judge("Delete1", ListDelete(L, 5, e1));
	cout << "输出删除操作后的动态分配顺序表:\n";
	PrintList(L);
	cout << "被删除的元素为:\n";
	cout << e1;
	cout << "\n";
	return 0;
}

标签:return,线性表,int,ElemType,SeqList,C++,length,动态分配,data
来源: https://blog.csdn.net/Wontoner/article/details/122224534