北林oj217题基于链式存储的逆序存储

描述

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

输入

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

输出

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

#include
#include
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;

	while (length < list->data.money) {
		cin >> a >> b >> c;
		p = new node;//分配新空间
		p->data.id = a;
		p->data.name = b;
		p->data.money = c;//赋值

		p->next = list->next;//头插法
		list->next = p;
		
		length++;//链表长度加一
		//cin >> a >> b >> c;
	}	
	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 turn_save (linklist &list) {
	node* p,*temp;//
	p = new node;
	temp = new node;
	p = list->next;
	list->next = NULL;
	while (p != NULL) {//前插
		  temp= p;
		  p = p->next;
		  temp->next = list->next;
		  list->next = temp;
		}

	}
	
int main() {
	linklist list;
	list = new node;
	int length;
	innit(list);//初始化链表
	cin >> length;
	list->data.money = length;
	creat_linklist(list);//创建单链表时直接前插法,就是逆序存储,
	//turn_save(list);//逆序存储
	print(list);
}


你可能感兴趣的:(北林oj,visual,studio,数据结构,c++)