1. 程式人生 > >ACM-單向鏈表的操作

ACM-單向鏈表的操作

amp sca stream dex node 單向 linklist pan break

數據表記錄包含表索引和數值,請對表索引相同的記錄進行合並,即將相同索引的數值進行求和運算,輸出按照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("\n"); 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; }

ACM-單向鏈表的操作