數據結構-線性表順序存儲表示

#include <cstdio>
#include <cstring>
#include <iostream> 
#define MAXSIZE 1005
#define OK 1
#define ERROR 0
typedef int Status;
using namespace std;
struct Book{
	char no[30];
	char name[30];
	double price;
	bool operator == (const Book &w) const {
		if (!strcmp(no, w.no)) return true;
		return false;
	} 
};
struct List {
	Book* elem; 
	int lenth; 
};
//初始化線性表 
Status initList(List &list) {
	list.elem = new Book[MAXSIZE];
	if (!list.elem) exit(0); //創建失敗
	list.lenth = 0;
	return OK; 
} 
//獲取線性表元素
Status getElem(List &list, int i, Book &elem) {
	if (i < 1 || i > list.lenth) return ERROR;
	elem = list.elem[i - 1];
	return OK;
} 
//獲取某個元素在線性表中的位置 不存在返回0 
int locateElem(List &list, Book &elem) {
	for (int i = 0; i < list.lenth; i++) {
		if (elem == list.elem[i]) return i + 1;
	} 
	return 0;
} 
//添加元素
Status insertElem(List &list, Book &elem) {
	if (list.lenth == MAXSIZE) return ERROR;
	list.elem[list.lenth++] = elem;
	return OK;
} 
//添加元素通過位置
Status insertElem(List &list, int i, Book &elem) {
	if (i < 1 || i > list.lenth + 1) return ERROR;
	for (int j = list.lenth - 1; j >= i - 1; j--) {
		list.elem[j + 1] = list.elem[j];
	}
	list.elem[i - 1] = elem;
	list.lenth++;
	return OK;
} 
//刪除指定位置的元素
Status deleteElem(List &list, int i) {
	if (i < 1 || i > list.lenth) return ERROR;
	for (int j = i - 1; j < list.lenth - 1; j++) list.elem[j] = list.elem[j + 1];
	list.lenth--;
	return OK;
} 
void output(Book &elem) {
	printf("no:%s name:%s price: %lf\n", elem.no, elem.name, elem.price);
}

List list;
int main() {
	initList(list);
	//添加元素
	Book books[100];
	for (int i = 1; i <= 3; i++) {
		Book book;
		scanf("%s%s%lf", book.no, book.name, &book.price);
		insertElem(list, i, book);
	} 
	for (int i = 0; i < list.lenth; i++) output(list.elem[i]);

	return 0;
} 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章