TZOJ 5640: 数据结构实验:仓库管理

描述

某百货公司仓库中有一批电视机,按其价格严格从低到高的次序,以链表(链表含头结点)的形式存储于计算机中,链表的每个结点表示同样价格的电视机台数。现在又有m台价格为x元的电视机准备入库,请将其加入到链表中(保证价格仍然严格从低到高)完成入库操作。

链表结点(Node类型)包含三个域,分别为价格、数量和指针域:

cost num next

题目部分代码已经完成,您只需要补充并提交以下函数:

void Add(Node* head, int m, int x);//其中head为链表头指针,m和x见题意

输入

输入数据的第一行为原始链表中结点的数目n。

接下来有n行,每行为2个正整数mi和xi,表示链表中各个结点的电视机台数和价格,其中x1<x2<x3<...<xn

下一行有两个正整数m和x,表示待入库的电视机台数和价格。

输出

输出插入完成后,从头到尾遍历链表并输出电视的台数和价格,每行一个结点。

样例输入

样例输出

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 struct Node
 4 {
 5     int num,money;
 6     Node *next;
 7 };
 8 void Printff(Node *head)
 9 {
10     Node *e=head->next;
11     while(e)
12     {
13         cout << e->num << " " << e->money << endl;
14         e=e->next;
15     }
16 }
17 void Add(Node* head, int m, int x)
18 {
19     Node *e=head->next;  //e为第一个节点
20     if(x<e->cost) //特判最小
21     {
22         Node *q=(Node*)malloc(sizeof(Node));
23         q->num=m,q->cost=x;
24         q->next=head->next;
25         head->next=q;
26         return;
27     }
28     while(x>e->cost)
29     {
30         e=e->next;
31         if(e==NULL)
32             break;
33     }
34     if(e==NULL)  //没有找到
35     {
36         Node *p=head->next;
37         while(p->next!=NULL)
38         {
39             p=p->next;
40         }
41         Node *q=(Node*)malloc(sizeof(Node));
42         q->num=m,q->cost=x,q->next=NULL;
43         p->next=q;
44     }
45     else   //在链表里面找打比他大的money
46     {
47         if(e->cost==x)
48         {
49             e->num+=m;
50         }
51         else if(e->cost>x)
52         {
53             Node *p=head->next;
54             while(p->next->cost<x&&p->next!=NULL)
55             {
56                 p=p->next;
57             }   //找到他的上一个节点
58             Node *t=(Node*)malloc(sizeof(Node));
59             t->num=m,t->cost=x;
60             t->next=p->next;
61             p->next=t;
62         }
63     }
64 }
65 Node *Creat()
66 {
67     int n,d1,d2;
68     Node *head,*rear;
69     head=new Node,head->next=NULL,rear=head;
70     cin>>n;
71     while(n--)
72     {
73         cin>>d1>>d2;
74         Node *e=new Node;
75         e->num=d1,e->money=d2,e->next=NULL;
76         rear->next=e;
77         rear=e;
78     }
79  
80     return head;
81 }
82 int main()
83 {
84     Node *head;
85     head=Creat();
86     int m,x;
87     cin>>m>>x;
88     Add(head,m,x);
89     Printff(head);
90 }
View Code
原文地址:https://www.cnblogs.com/qq-1585047819/p/10539769.html