描述
定义一个包含图书信息(书号、书名、价格)的链表,读入相应的图书数据来完成图书信息表的创建,然后根据指定的待入库的新图书的位置和图书的信息,将新图书插入到图书表中指定的位置上,最后输出新图书入库后的所有图书的信息。
输入
总计n+3行。首先输入n+1行,其中,第一行是图书数目n,后n行是n本图书的信息(书号、书名、价格),每本图书信息占一行,书号、书名、价格用空格分隔,价格之后没有空格。其中书号和书名为字符串类型,价格为浮点数类型。之后输入第n+2行,内容仅为一个整数,代表待入库的新图书的位置序号。最后输入第n+3行,内容为新图书的信息,书号、书名、价格用空格分隔。
输出
若插入成功: 输出新图书入库后所有图书的信息(书号、书名、价格),总计n+1行,每行是一本图书的信息,书号、书名、价格用空格分隔。其中价格输出保留两位小数。 若插入失败: 只输出以下一行提示:抱歉,入库位置非法!
输入样例 1
7 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 2 9787822234110 The-C-Programming-Language 38.00
输出样例 1
9787302257646 Data-Structure 35.00 9787822234110 The-C-Programming-Language 38.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
输入样例 2
7 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 9 9787822234110 The-C-Programming-Language 38.00
输出样例 2
Sorry,the position to be inserted is invalid!
#include<bits/stdc++.h>
#include<string.h>
using namespace std;
struct Book{
char id[50];
char name[50];
float price;
Book *next;
};
int main(){
int n;
cin>>n;
Book *head=NULL,*tail=NULL,*temp=NULL,*p=NULL;
for(int i=0;i<n;i++){
temp=new Book;
cin>>temp->id>>temp->name>>temp->price;
if(head==NULL&&tail==NULL){
head=temp;
tail=temp;
}
else{
tail->next=temp;
tail=temp;
}
}
int m;
cin>>m;
if(m>n||m<=0){
cout<<"Sorry,the position to be inserted is invalid!";
}
else{
temp=new Book;
cin>>temp->id>>temp->name>>temp->price;
p=head;
for(int i=1;i<m-1;i++){
p=p->next;
}
temp->next=p->next;
p->next=temp;
temp=head;
while(temp!=NULL){
cout<<temp->id<<" "<<temp->name<<" "<<fixed<<setprecision(2)<<temp->price<<endl;
temp=temp->next;
}
}
}