将之前一段时间在牛客上刷的题给大家分享一下。其中一道题是“合并表记录”,现在将通过的代码贴一下,供大家参考。
数据表记录包含表索引和数值(int范围的正整数),请对表索引相同的记录进行合并,即将相同索引的数值进行求和运算,输出按照key值升序进行输出。
#include <stdlib.h> #include <stdio.h> struct node { int key; int value; struct node *prev; struct node *next; }; //struct item //{ // struct node s_node; // struct item *prev; // struct item *next; //}; void insertprev(struct node * s_item,struct node * insert_item) { insert_item->prev = s_item->prev; s_item->prev->next = insert_item; insert_item->next = s_item; s_item->prev = insert_item; }; int main() { struct node list; int count; int key; int value; scanf("%d",&count); list.next=NULL; list.prev=NULL; list.key=0; list.value=0; if(count==1) { scanf("%d %d",&key,&value); printf("%d %d",key,value); return 0; } else { scanf("%d %d",&key,&value); list.next = (struct node *)malloc(sizeof(struct node)); list.next->prev = &list; list.next->key = key; list.next->value = value; int i=1; for(i=1;i<count;i++) { struct node * s_item = list.next; scanf("%d %d",&key,&value); do { if(key<s_item->key) { struct node * n_item = (struct node *)malloc(sizeof(struct node)); n_item->key = key; n_item->value = value; insertprev(s_item,n_item); break; } else if(key==s_item->key) { s_item->value+=value; break; } else if(s_item->next==NULL) { struct node * n_item = (struct node *)malloc(sizeof(struct node)); n_item->key = key; n_item->value = value; n_item->next=s_item->next; n_item->prev=s_item; s_item->next=n_item; break; } else s_item=s_item->next; }while(1); } } struct node * l_item = list.next; while(l_item!=NULL) { printf("%d %d\n",l_item->key,l_item->value); l_item = l_item->next; } return 0; }