用链表处理表索引相同的记录进行合并,即将相同索引的数值进行求和运算,输出按照key值升序进行输出
链表排序所用的思想是用数组接受链表数据域的值,然后对数组排序。如果有需要,将排完序的数组再放入新建链表中
#include <stdio.h>
#include <iostream>
#include <string.h>
using namespace std;
void insertsort(int p[][500], int N);
struct list {
int index;
int value;
struct list* next;
};
void listsort(list* listptr, int a[][500], int* len);
int main() {
int num,i, a[2][500], length;
memset(a, 0, sizeof(a));
struct list* listptr;
struct list* listptr1;
struct list* nowptr;
struct list* preptr;
struct list* head;
cin >> num;
i = num;
listptr = (struct list*)malloc(sizeof(struct list));
if (listptr == NULL)
return 0;
else
{
listptr->index = 0;
listptr->value = 0;
}
head = listptr;
if (num == 0)
listptr->next = NULL;
else
{
while (i--) {
listptr1 = (struct list*)malloc(sizeof(struct list));
listptr->next = listptr1;
(void)scanf("%d %d", &listptr1->index, &listptr1->value);
listptr = listptr->next;
}
listptr1->next = NULL;
}
listptr = head->next;// 处理链表相同索引的值
for (i = 0; i < num && listptr->next != NULL; i++) {
preptr = listptr;
for (nowptr = preptr->next; nowptr != NULL; ) {
if (nowptr->index == listptr->index) {
listptr->value += nowptr->value;
preptr->next = nowptr->next;//删除这个节点
nowptr= nowptr->next;//把当前节点移动到写一个节点
//这一时候,preptr不动
}
else {
preptr = nowptr;
nowptr = nowptr->next;
//如果不相同,preptr和nowptr都要移动
}
}
listptr = listptr->next;
}
//链表排序
listsort(head, a, &length);
//输出链表的值
for (i = 0; i < length; i++) {
cout << a[0][i] << ' ' << a[1][i] << endl;
}
return 0;
}
void listsort(list* listptr, int a[][500], int* len) {
//用数组的形式实现排序
int i;
memset(a, 0, sizeof(a));
list* tmpptr1;
list* tmpptr2;
tmpptr1 = listptr->next;
for (i = 0; tmpptr1 != NULL; i++) {
a[0][i] = tmpptr1->index;
a[1][i] = tmpptr1->value;
tmpptr1 = tmpptr1->next;
}
//共有i个元素
*len = i;
insertsort(a, i);
}
void insertsort(int p[][500], int N) {
int tmp1, tmp2, i, j;
for (i = 1; i < N; i++) {
tmp1 = *(*(p + 0) + i);
tmp2= *(*(p + 1) + i);
for (j = i;j>0&&(*(*(p+0)+j-1)>tmp1);j--) {
*(*(p + 0) + j) = *(*(p + 0) + j - 1);
*(*(p + 1) + j) = *(*(p + 1) + j - 1);
}
*(*(p + 0) + j) = tmp1;
*(*(p + 1) + j) = tmp2;
}
}