基于链存储结构的图书信息表的图书去重
描述
出版社出版的任何一本图书的书号(ISBN)都是唯一的,即图书表中不允许包含书号重复的图书。定义一个包含图书信息(书号、书名、价格)的链表,读入相应的图书数据来完成图书信息表的创建(书号可能重复),然后进行图书的去重,即删除书号重复的图书(只保留第一本),最后输出去重后所有图书的信息。
输入
总计输入n+1行,其中,第一行是图书数目n,后n行是n本图书的信息(书号、书名、价格),每本图书信息占一行,书号、书名、价格用空格分隔,价格之后没有空格(书号可能重复)。其中书号和书名为字符串类型,价格为浮点数类型。
输出
总计输出m+1行(m≤n),其中,第一行是去重后的图书数目,后m行是去重后图书的信息(书号、书名、价格),每本图书信息占一行,书号、书名、价格用空格分隔,其中价格输出保留两位小数。
9
9787302257646 Data-Structure 35.00
9787302164340 Operating-System 50.00
9787302219972 Software-Engineer 32.00
9787302203513 Database-Principles 36.00
9787810827430 Discrete-Mathematics 36.00
9787302257800 Data-Structure 62.00
9787811234923 Compiler-Principles 62.00
9787811234923 Compiler-Principles 62.00
9787822234110 The-C-Programming-Language 38.00
输出:
8 9787302257646 Data-Structure 35.00 9787302164340 Operating-System 50.00 9787302219972 Software-Engineer 32.00 9787302203513 Database-Principles 36.00 9787810827430 Discrete-Mathematics 36.00 9787302257800 Data-Structure 62.00 9787811234923 Compiler-Principles 62.00 9787822234110 The-C-Programming-Language 38.00
#include<iostream>
#include<iomanip>
using namespace std;
typedef struct book {
string id;
string name;
float money;
};
typedef struct node {
book data;
struct node* next;
}node, * linklist;
void innit(linklist& list) {
list = new node;//分配大小为node的空间
list->next = NULL;
list->data.money = 0;//头结点存放链表长度;
}
//尾插法构建单链表
void creat_linklist(linklist& list) {
node* p = NULL;//插入节点
string a, b;
float c;
int length = 0;
node* r;
r = new node;
r = list;
while (length < list->data.money) {
cin >> a >> b >> c;
p = new node;//分配新空间
p->data.id = a;
p->data.name = b;
p->data.money = c;//赋值
r->next = p;//尾插法
r = r->next;
length++;//链表长度加一
//cin >> a >> b >> c;
}
r->next = NULL;
p = NULL;//一定要先置空,再回收指针
delete p;//回收指针
}
//输出
void print(linklist list) {
node* p;
p = list;
while (p->next != NULL) {
p = p->next;
cout << p->data.id << " " << p->data.name << " " << fixed << setprecision(2) << p->data.money << endl;
}
p = NULL;
delete p;
}
void deduplication(linklist& list) {
node* current;//当前指针
node* search=NULL;//搜寻指针
current = new node;
search = new node;
current = list->next;//初始为第一个结点
while (current != NULL) {
search = current;
while (search->next != NULL) {//开始搜寻
if (current->data.id == search->next->data.id) {
node* del = NULL;//回收结点
del = new node;
del = search->next;
search->next = search->next->next;
delete del;//回收重复指针
list->data.money--;
}
else search = search->next;
}
current = current->next;
}
}
int main() {
linklist list;//图书信息表
int length;//图书信息表 表长
list = new node;
cin >> length;
list->data.money = length;//将表长存放于头结点中
creat_linklist(list);//创建单链表
deduplication(list);
cout << list->data.money << endl;
print(list);
}