北林oj215题基于链式存储结构的图书信息表的降序排序

描述

定义一个包含图书信息(书号、书名、价格)的链表,读入相应的图书数据完成图书信息表的创建,然后将图书按照价格降序排序,逐行输出排序后每本图书的信息。

输入

输入n+1行,前n行是n本图书的信息(书号、书名、价格),每本图书信息占一行,书号、书名、价格用空格分隔,价格之后没有空格。最后第n+1行是输入结束标志:0 0 0(空格分隔的三个0)。其中书号和书名为字符串类型,价格为浮点数类型。

输出

总计n行,每行是一本图书的信息(书号、书名、价格),书号、书名、价格用空格分隔。其中价格输出保留两位小数。

#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;//插入节点
	node* r;//尾指针
	innit(list);//初始化链表
	r = list;//尾指针指向头结点
	string a, b;
	float c;
	cin >> a >> b >> c;

	while (a != "0" && b != "0" && c != 0) {
		p = new node;//分配新空间
		p->data.id = a;
		p->data.name = b;
		p->data.money = c;

		r->next = p;
		r = r->next;
		list->data.money++;//链表长度加一
		cin >> a >> b >> c;
	}
	r->next = NULL;
	p = NULL;//一定要先置空,再回收指针
	r = NULL;
	delete p;//回收指针
	delete r;
}
//输出
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 jiangxu(linklist& list) {
	node* p = NULL;//正待排序结点
	p = new node;
	p = list->next;
	node * r = NULL;//在有序序列中查找 待排序结点的位置
	node * f = NULL;
	f = new node;
	r = new node;
	if (p->next != NULL)//链表不只有一个结点
		p = p->next;//第二个结点
	  list->next->next = NULL;//已有序队列尾端置空
	while (p != NULL) {
		//p = p->next;			
			float inserting = p->data.money;//待插入图书价格
				r= list->next;//搜索指针前指针
				f = list;//搜索指针后指针
				node* q = NULL;//临时指针
				q = new node;
				q = p;
				p = p->next;//下一个待插图书信息
				while (1) {
					float inserted = r->data.money;
					
					if (inserting > inserted) {
						//头插,在inserted 前面
						q->next = r;
						f->next = q;	
						break;
					}
					if (inserting < inserted && r->next!=NULL) { r = r->next; f = f->next; }
					if (inserting == inserted || r->next == NULL) {//相等or最小,后插
						q->next = r->next;   r->next = q;
						break;
					}
					
				}	
	}
}
int main() {
	linklist list;
	creat_linklist(list);
	//cout << list->data.money << endl;//输出 链表长度
	jiangxu(list);
	print(list);
	return 0;
}

  • 13
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值