描述
定义一个包含图书信息(书号、书名、价格)的链表,读入相应的图书数据来完成图书信息表的创建,然后根据指定的待入库的新图书的位置和图书的信息,将新图书插入到图书表中指定的位置上,最后输出新图书入库后的所有图书的信息。
输入
总计n+3行。首先输入n+1行,其中,第一行是图书数目n,后n行是n本图书的信息(书号、书名、价格),每本图书信息占一行,书号、书名、价格用空格分隔,价格之后没有空格。其中书号和书名为字符串类型,价格为浮点数类型。之后输入第n+2行,内容仅为一个整数,代表待入库的新图书的位置序号。最后输入第n+3行,内容为新图书的信息,书号、书名、价格用空格分隔。
输出
若插入成功:
输出新图书入库后所有图书的信息(书号、书名、价格),总计n+1行,每行是一本图书的信息,书号、书名、价格用空格分隔。其中价格输出保留两位小数。
若插入失败:
只输出以下一行提示:抱歉,入库位置非法!
此题纠正了之前链表创建,结尾没有NULL的问题,就是用一个pre前点指针。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| #include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<cmath> #define OK 1 using namespace std; typedef struct { char no[20]; char name[50]; float price; }Book; typedef struct LNode { Book data; struct LNode *next; }LNode,*LinkList; LinkList L; bool InintList(LinkList &L) { L=new LNode; L->next=NULL; return OK; } int main() { int num; InintList(L); cin>>num; LNode *pre=L;//pre非常关键,这个是为了让链表最后一端为NULL for(int i=0;i<num;i++) { LNode *p=new LNode; scanf("%s%s%f",p->data.no,p->data.name,&p->data.price); pre->next=p; pre=p; } pre->next=NULL; int position=0; cin>>position; pre=L; LNode *NEW=new LNode; LNode *it=L->next; scanf("%s%s%f",NEW->data.no,NEW->data.name,&NEW->data.price); if(position<=0||position>=(num+1)) { printf("Sorry, the storage location is illegal!\n"); } else {//之前创建的链表没有NULL节点,不太好,这里会有问题,但是现在有NULL了 for(int i=1;i<=num+1;i++,pre=pre->next,it=it->next) { if(i==position) { pre->next=NEW; NEW->next=it; break; } } it=L->next; while(it) { printf("%s %s %.2f\n",it->data.no,it->data.name,it->data.price); it=it->next; } } return 0; }
|