#include<iostream>
#include<string>
#include<fstream>
#include<iomanip>
using namespace std;
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int Status;
typedef int ElemType;
struct Book {
string id;
string name;
double price;
};
typedef struct DuLNode {
Book data;
struct DuLNode *prior;
struct DuLNode *next;
} DuLNode, *DuLinkList;
string head_1, head_2, head_3;
int length;
Status InitDuList_L(DuLinkList &L) {
L = new DuLNode;
L->next = NULL;
L->prior = NULL;
return OK;
}
DuLNode *GetElemP_DuL(DuLinkList L, int i) {
int j;
DuLinkList p;
p = L->next;
j = 1;
while (j < i && p) {
p = p->next;
++j;
}
if (!p || j > i)
return NULL;
return p;
}
Status ListInsert_DuL(DuLinkList &L, int i, Book e) {
DuLinkList s, p;
if (!(p = GetElemP_DuL(L, i)))
return ERROR;
if (i == 1) {
s = new DuLNode;
s->data = e;
DuLinkList p = L->next;
L->next = s;
s->prior = L;
s->next = p;
p->prior = s;
++length;
} else if (i == length) {
s = new DuLNode;
s->data = e;
DuLinkList p = L;
while (p->next)
p = p->next;
p->next = s;
s->prior = p;
s->next = NULL;
++length;
} else {
s = new DuLNode;
s->data = e;
s->prior = p->prior;
p->prior->next = s;
s->next = p;
p->prior = s;
++length;
}
return OK;
}
Status ListDelete_DuL(DuLinkList &L, int i) {
DuLinkList p;
if (!(p = GetElemP_DuL(L, i)))
return ERROR;
if (i == 1)
L = L->next;
else if (i == length) {
p->prior->next = NULL;
delete p;
--length;
return OK;
} else {
p->prior->next = p->next;
p->next->prior = p->prior;
delete p;
--length;
return OK;
}
}
void CreateDuList_L(DuLinkList &L) {
DuLinkList r, p;
L = new DuLNode;
L->next = NULL;
r = L;
length = 0;
fstream file;
file.open("book.txt");
if (!file) {
cout << "未找到相关文件,无法打开!" << endl;
exit(ERROR);
}
file >> head_1 >> head_2 >> head_3;
while (!file.eof()) {
p = new DuLNode;
file >> p->data.id >> p->data.name >> p->data.price;
p->next = NULL;
r->next = p;
r = p;
p->prior = L->prior;
L->prior = p;
length++;
}
file.close();
}
int main() {
int a, choose;
Book e;
DuLinkList L, p;
cout << "1. 建立\n";
cout << "2. 输入\n";
cout << "3. 插入\n";
cout << "4. 删除\n";
cout << "5. 输出\n";
cout << "0. 退出\n\n";
choose = -1;
while (choose != 0) {
cout << "请选择:";
cin >> choose;
switch (choose) {
case 1:
if (InitDuList_L(L))
cout << "成功建立双向链表!\n\n";
break;
case 2:
CreateDuList_L(L);
cout << "输入 book.txt 信息完毕\n\n";
break;
case 3:
cout << "请输入两个数分别代表插入的位置和数值(书的信息:编号&书名&价格):";
cin >> a;
cin >> e.id >> e.name >> e.price;
if (ListInsert_DuL(L, a, e))
cout << "插入成功.\n\n";
else
cout << "插入失败!\n\n";
break;
case 4:
cout << "请输入所要删除的书籍的位置:";
cin >> a;
if (ListDelete_DuL(L, a))
cout << "删除成功!\n\n";
else
cout << "删除失败!\n\n";
break;
case 5:
cout << "当前图书系统信息读出:\n";
p = L->next;
while (p) {
cout << left << setw(15) << p->data.id << "\t" << left << setw(
50) << p->data.name << "\t" << left << setw(5)
<< p->data.price << endl;
p = p->next;
}
cout << endl;
break;
}
}
return 0;
}