线性表——数组实现

#include <iostream>
#include <cstdio>
#include <cstdlib>

using namespace std;

const int MAXSIZE = 20;
using ElemType = int;

// 线性表结构 
class SqList {
public:
	ElemType data[MAXSIZE];
	int length;
}; 

// 创建线性表list 
SqList createList()
{
	SqList list;
	return list;
}

// 在尾部增加元素 
void addElem(SqList &list, int val)
{
	list.data[list.length] = val;
	list.length++;
}

// 删除线性表list中第i个位置 
void delElem(SqList &list, int i)
{
	if (list.length == 0 || i > list.length || i < 1)
	{
		cout << "fail to del elem
";
		return;
	}
	if (i < list.length) {
		for (int k = i - 1; k < list.length - 1; k++) {
			list.data[k] = list.data[k+1];
		}
	}
	list.length--;
}

// 返回线性表list中的第i个位置的元素 
bool getElem(const SqList &list, int i, ElemType &e)
{
	if (list.length == 0 || i < 1 || i > list.length) 
		return false;
	e = list.data[i-1];
	return true;
}

void printElem(const SqList &list)
{
	if (list.length == 0) {
		cout << "No elem
";
		return;
	}
	for (int i = 0; i != list.length; i++)
	{
		if (i != 0)
			cout << "<-"; 
		cout << list.data[i] << " ";
	}
	cout << endl;
}

void sys()
{
	printf("	---------线 性 表 数 组 ----------
");
	printf("	--------1 新 建 线 性 表 ---------
");
	printf("	--------2 增 加 元 素 ------------
");
	printf("	--------3 删 除 元 素 ------------
");
	printf("	--------4 查 看 元 素 ------------
");
	printf("	--------5 退 出 系 统 ------------
"); 
	printf("->");
}

void startList()
{
	SqList list;
	int seq, val;
	while(1) {
		sys();
		cin >> seq;
		switch(seq) {
			case 1:
				list = createList();
				break;
			case 2:
				cout << "请输入要添加到尾部的值:";
				cin >> val;
				addElem(list, val);
				break;
			case 3:
				cout << "请输入你要删除的元素在线性表的位置:";
				cin >> val;
				delElem(list, val);
				break;
			case 4:
				printElem(list);
				break;
			case 5:
				exit(0);
			default:
				cout << "please input num(1~5)
";
				break;
		} 
	}
} 

int main()
{
	startList();
}

  

原文地址:https://www.cnblogs.com/xzxl/p/8641977.html