题解 | #合并表记录#
合并表记录
http://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201
用链表,自定义含有两个数据的节点就行了。在输入数据的同时按大小顺序生成和连接节点,就不用再排序了。思路比较简单,代码好写。不过运行速度平平,可能是因为用了链表的关系吧。
#include<stdio.h>
struct node{
int data1;
int data2;
struct node *next;
};
int main(){
struct node *p;
struct node *head;
head=(struct node *)malloc(sizeof(struct node));
head->data1=-1;
head->data2=0;
head->next=NULL;
p=head;
int count;
scanf("%d", &count);
for(int i=0; i<count; i++){
int x;
scanf("%d", &x);
int y;
scanf("%d", &y);
int sign=0;
struct node *past=head;
for(p=head; p!=NULL; p=p->next){
if(p->data1==x){
p->data2+=y;
break;
}
else if(p->data1>x){
sign=1;
break;
}
past=p;
}
if(sign==1||p==NULL){
struct node *q;
q=(struct node *)malloc(sizeof(struct node));
q->data1=x;
q->data2=y;
past->next=q;
q->next=p;
}
}
head=head->next;
while(head){
printf("%d %d\n", head->data1, head->data2);
head=head->next;
}
return 0;
}

