• ACM-单向链表的操作


    数据表记录包含表索引和数值,请对表索引相同的记录进行合并,即将相同索引的数值进行求和运算,输出按照key值升序进行输出。

    输入描述:

    先输入键值对的个数
    然后输入成对的index和value值,以空格隔开

    输出描述:

    输出合并后的键值对(多行)

    #include <iostream>
    #include <stdio.h>
    
    using namespace std;
    
    struct table{
        int id;
        int value;
        struct table *next;
    };
    
    typedef struct table *LinkList;
    
    void AddNode(LinkList *HeadList,int id,int value,int i)
    {
        LinkList p = *HeadList;
        for(int j = 0;j < i;j++)
            p = p->next;
        LinkList node = (LinkList)malloc(sizeof(struct table));
        p->next = node;
        node->id = id;
        node->value = value;
        node->next = NULL;
    
    }
    void swap(LinkList *Node1,LinkList *Node2)
    {
        LinkList Node3 = (LinkList)malloc(sizeof(struct table));
        LinkList node1 = *Node1;
        LinkList node2 = *Node2;
    
        Node3->id = node1->id;
        Node3->value = node1->value;
    
        node1->id = node2->id;
        node1->value = node2->value;
    
        node2->id = Node3->id;
        node2->value = Node3->value;    
    }
    void Rank(LinkList *HeadList)
    {
        LinkList p = *HeadList;
        p = p->next;
        while(p != NULL){
            LinkList p_p = *HeadList;
            p_p = p_p->next;
            while(p_p != NULL){
                if(p->id < p_p->id)
                    swap(&p,&p_p);
                p_p = p_p->next;
            }
            p = p->next;
        }
    }
    void ListPrint(LinkList *HeadList){
        LinkList p = *HeadList;
        p = p->next;
        while(p != NULL){
            while(p->id == p->next->id){
                if(p->next != NULL)
                {
                    p->next->value += p->value;
                    p = p->next;
                }
                else
                    break;
            }
            printf("%d %d",p->id,p->value);
            printf("
    ");
            p = p->next;
            
        }
    }
    int main()
    {
        int id,value;
        LinkList list = (LinkList)malloc(sizeof(struct table));
        int n;
        list->id = 0;
        list->value = 0;
        while(scanf("%d",&n) != EOF){
            for(int i = 0;i < n;i++){
                scanf("%d %d",&id,&value);
                AddNode(&list,id,value,i);
            }
            Rank(&list);
            ListPrint(&list);
        }
        free(list);
        return 0;
    }
  • 相关阅读:
    相机中白平衡的算法模拟实现
    双边滤波算法的简易实现bilateralFilter
    图像处理卷积算法实现
    最快的3x3中值模糊
    黑米手机抢购软件通杀破解补丁
    分享一款12306购票软件
    快速堆栈模糊算法
    大数据(1)---大数据及HDFS简述
    springboot自动装配(3)---条件注解@Conditional
    随机瓜分百万红包
  • 原文地址:https://www.cnblogs.com/qiang-wei/p/9321119.html
Copyright © 2020-2023  润新知