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,表示待入库的电视机台数和价格。

输出 

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

样例输入

3
1 1000
3 2000
2 3000
10 2100

样例输出

1 1000
3 2000
10 2100
2 3000

PS:附赠调试代码,/**/符号自行删除哦

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
/*
typedef struct Node
{
    int cost,num;
    struct Node *next;
}Node;
Node *CreateLinkList(int n)  //头结点数据域为空
{
    int i;
    Node *pre,*q,*head;
    head = (Node*)malloc(sizeof(Node));
    pre = head;
    pre->next = NULL;
    for(i=0; i<n; i++)
    {
        q = (Node*)malloc(sizeof(Node));
        scanf("%d %d",&q->num,&q->cost);
        pre->next = q;
        pre = q;
        q->next = NULL;
    }
    return head;
}
*/

void Add(Node* head, int m, int x)
{
    Node *pre,*p,*q;
    pre = head->next;
    if(pre->cost > x) //要插在头结点后面,即第一个节点
    {
        q = (Node*)malloc(sizeof(Node));
        q->num = m;
        q->cost = x;
        q->next = pre;
        head->next =q;
        return;
    }
    while(pre->next && pre->cost<x) //寻找x的位置,等于在原位置
    {
        if(pre->next->cost>x) break; // x 比下一个值要小,结束
        pre = pre->next;
    } //假如运行到尾结点,即最后节点停止

        if(pre->cost == x)  //两个值相等,就相加
            pre->num = pre->num + m;

        else{
            q = (Node*)malloc(sizeof(Node));
            q->num = m;
            q->cost = x;
            q->next = pre->next;
            pre->next = q;
        }


}
/*
void PrintLinkList(Node *head)

 {

 Node *p = head->next, *q;
    while(p)
    {
        printf("%d %d\n", p->num,p->cost);
        q = p;
        p = p->next;
        free(q);
    }
    free(head);
}
int main()
{
    int n,m,x;
    scanf("%d",&n);
    Node* head = CreateLinkList(n);
    scanf("%d %d",&m,&x);
    Add(head, m, x);
    PrintLinkList(head);
    return 0;
}
*/

猜你喜欢

转载自www.cnblogs.com/lenka-lyw/p/10891263.html