1. 程式人生 > 實用技巧 >最短路徑(3)

最短路徑(3)

執行環境:Microsoft Visual studio 2017

語言:C++

#include <iostream>
#define MAXSIZE 100

using namespace std;

//線性表的順序儲存
typedef int ElemType;
typedef struct {
	ElemType data[MAXSIZE];
	int length;
}LinearList;

void InitList(LinearList &L);
int length(LinearList &L);
int LocateElem(LinearList &L, int e);
int getElem(LinearList &L, int i);
bool ListInsert(LinearList &L, int i, int e);
bool ListDelete(LinearList &L, int i, int &e);
void PrintList(LinearList L);
bool Empty(LinearList L);
void DestoryList(LinearList &L);

int main() {
	LinearList L;
	//初始化
	InitList(L);
	//插入
	ListInsert(L, 1, 11);
	ListInsert(L, 2, 22);
	ListInsert(L, 3, 33);
	PrintList(L);
	int e;
	ListDelete(L, 2, e);
	cout << e << endl;
	PrintList(L);
}

//初始化
void InitList(LinearList &L) {
	for (int i = 0; i < MAXSIZE; i++)
	{
		L.data[i] == 0;
	}
	L.length = 0;
}

//求表長
int length(LinearList &L) {
	return L.length;
}

//按值查詢操作
int LocateElem(LinearList &L, int e) {
	for (int i = 0; i < L.length; i++)
	{
		//返回線性表的第幾個元素的位置
		if (L.data[i] == e)	return i + 1;
	}
	return -1;
}

//按位查詢操作
int getElem(LinearList &L, int i) {
	if (i<1 || i>L.length) {
		return -1;
	}
	return L.data[i - 1];
}

//插入操作
bool ListInsert(LinearList &L, int i, int e) {
	if (i<1 || i>L.length + 1) {
		return false;
	}
	if (L.length == MAXSIZE) {
		return false;
	}
	for (int j = L.length; j >= i; j--)
	{
		L.data[j] = L.data[j - 1];
	}
	L.data[i - 1] = e;
	L.length++;
	return true;
}

//刪除操作
bool ListDelete(LinearList &L, int i, int &e) {
	if (i<1 || i>L.length) {
		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;
}

//輸出
void PrintList(LinearList L) {
	for (int i = 1; i <= L.length; i++)
	{
		cout << i << ":\t" << L.data[i - 1] << endl;
	}
}

//判空
bool Empty(LinearList L) {
	if (L.length == 0)	return true;
	return true;
}

//銷燬順序表
void DestoryList(LinearList &L) {
	free(&L);
}