HJ8 合并表记录

描述
数据表记录包含表索引index和数值value(int范围的正整数),请对表索引相同的记录进行合并,即将相同索引的数值进行求和运算,输出按照index值升序进行输出。

提示:
0 <= index <= 11111111
1 <= value <= 100000

输入描述:
先输入键值对的个数n(1 <= n <= 500)
接下来n行每行输入成对的index和value值,以空格隔开

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

示例1

输入:
	4
	0 1
	0 2
	1 2
	3 4
输出:
	0 3
	1 2
	3 4

## 示例2

```c
输入:
	3
	0 1
	0 2
	8 9
输出:
	0 3
	8 9

实现

#include 
#include 
#include 

struct kvList {
    int key;
    int value;
    struct kvList *next;
};

struct kvList *createListNode()
{
    struct kvList *node = (struct kvList *)malloc(sizeof(struct kvList));
    if (node == NULL) {
        printf("malloc fail\n");
        return NULL;
    }
    memset(node, 0x00, sizeof(struct kvList));
    return node;
}

int insertNodeToList(struct kvList *head, int key, int value)
{
    struct kvList *tmp = head;
    struct kvList *node = NULL;
    
    node = createListNode();
    node->key = key;
    node->value = value;
//    printf("input kv[%d: %d], next: %p, %p, %p\n", key, value, tmp, head, node);
    while ((tmp->next != NULL) && (tmp->next->key < key)) {
        tmp = tmp->next;
    }

 //   printf("kv[%d: %d], %p\n", tmp->key, tmp->value, tmp);
    if (tmp->next == NULL) { // 没找到,value最大
        tmp->next = node;
   //     printf("inset node to list, kv[%d: %d], %p\n", key, value, node);
    } else if (tmp->next->key == key) {
        tmp->next->value += value;
  //      printf("same key, kv[%d: %d], %p\n", key, tmp->next->value, node);
    } else {
 //       printf("more than key, kv[%d: %d], %p\n", key, value, node);
        node->next = tmp->next;
        tmp->next = node;
    }
    return 0;
}

void printfList(struct kvList *head)
{
    struct kvList *tmp = head->next;
    while (tmp->next != NULL) {
 //       printf("Display kv[%d: %d], %p\n", tmp->key, tmp->value, tmp);
        printf("%d %d\n", tmp->key, tmp->value);
        tmp = tmp->next;
    }
 //   printf("Display kv[%d: %d], %p\n", tmp->key, tmp->value, tmp);
    printf("%d %d\n", tmp->key, tmp->value);
}

int main()
{
    int num;
    int key, value;
    
    struct kvList *head = createListNode();
    scanf("%d", &num);
//    printf("num: %d, head: %p\n", num, head);
    
    for (int i = 0; i < num; i++) {
        scanf("%d %d\n", &key, &value);
        insertNodeToList(head, key, value);
    }
    printfList(head);
    // freeList();
    return 0;
}

HJ8 合并表记录_第1张图片

你可能感兴趣的:(牛客网,-,练习,c语言,链表,数据结构)