#include <iostream>
#include <cstring>//将一些隐藏变量编入命名空间,修正一些C++编译器认为Bug的代码
using namespace std;
const int M = 50;//定义最大数据存储数量为1000
//图书信息的结构体
typedef struct {
char no[13]; //13位书号
char name[20]; //书名
double price; //价格
}Book;
//定义数据结构——链表,由于图书信息经常需要查找,在顺序表和链表中,链表更适合存储经常需要查找的数据
typedef struct LNode {
Book data; //数据域
struct LNode* next; //指针域
}LNode, * LinkList;
LNode* first; //定义链表头结点
//逐个显示图书表中所有图书的相关信息
void bookOut() {
cout << "管理系统中全部图书信息如下:" << endl;
LNode* p = first->next;
while (p) {
cout << p->data.no << " " << p->data.name << " " << p->data.price << endl;
p = p->next;
}
}
int main() {
Book book[M];//定义图书存储空间
int count = 0, n;
bool tag = true;
while (tag) {
cout << "请输入初始书本数量(0~50):" << endl;
cin >> n;//初始书本数量
if (n >= 0 && n <= M) {
while (count < n) {
cout << "请输入书号,书名和价格(中间以空格符隔开)" << endl;
cin >> book[count].no;
cin >> book[count].name;
cin >> book[count].price;
count++;
}
tag = false;
}
else { cout << "输入不正确" << endl; }
}
//构造后接方式单链表
first = new LNode();
first->next = NULL;
LNode* r = first, * s;
for (int i = 0; i < M; i++) { //r为尾指针
s = new LNode();
s->data = book[i];
//s->next = NULL;
r->next = s;
r = s;
}
r->next = NULL;
bookOut();
}
修改如下:
#include <iostream>
#include <cstring>//将一些隐藏变量编入命名空间,修正一些C++编译器认为Bug的代码
using namespace std;
const int M = 50;//定义最大数据存储数量为1000
//图书信息的结构体
typedef struct {
char no[13]; //13位书号
char name[20]; //书名
double price; //价格
}Book;
//定义数据结构——链表,由于图书信息经常需要查找,在顺序表和链表中,链表更适合存储经常需要查找的数据
typedef struct LNode {
Book data; //数据域
struct LNode* next; //指针域
}LNode, * LinkList;
LNode* first; //定义链表头结点
//逐个显示图书表中所有图书的相关信息
void bookOut() {
cout << "管理系统中全部图书信息如下:" << endl;
LNode* p = first->next;
while (p != NULL) {
cout << p->data.no << " " << p->data.name << " " << p->data.price << endl;
p = p->next;
}
}
int main() {
Book book[M];//定义图书存储空间
int count = 0, n;
bool tag = true;
while (tag) {
cout << "请输入初始书本数量(0~50):" << endl;
cin >> n;//初始书本数量
if (n >= 0 && n <= M) {
while (count < n) {
cout << "请输入书号,书名和价格(中间以空格符隔开)" << endl;
cin >> book[count].no;
cin >> book[count].name;
cin >> book[count].price;
count++;
}
tag = false;
}
else { cout << "输入不正确" << endl; }
}
//构造后接方式单链表
first = new LNode();
first->next = NULL;
LNode* r = first, * s;
for (int i = 0; i < n; i++) //此处 M 改为 n 有几本初始化基本,不要一下初始化完全。
{ //r为尾指针
s = new LNode();
s->data = book[i];
r->next = s;
r = s;
}
r->next = NULL;
bookOut();
//此时退出申请的空间还未释放,最好去delete掉
return 0;
}