数据结构-线性表顺序存储表示
程序员文章站
2024-03-20 14:33:10
...
#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;
}
下一篇: 文件下载中文乱码问题后端