题解 | #合并表记录#
合并表记录
https://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201?tpId=37&tqId=21231&rp=1&ru=/exam/oj/ta&qru=/exam/oj/ta&sourceUrl=%2Fexam%2Foj%2Fta%3Fpage%3D1%26tpId%3D37%26type%3D37&difficulty=undefined&judgeStatus=undefined&tags=&title=
#include <stdio.h> #include <stdlib.h> struct hashTableManager{ int size; struct hashTableNode* pHead; }; struct hashTableNode{ int index; int value; struct hashTableNode* pNext; }; int main() { int number,index,value=0; int isIndexNew=1; struct hashTableManager manager = {0}; struct hashTableNode *pcurrent_node; scanf("%d", &number); manager.size=0; manager.pHead = (struct hashTableNode*)malloc(sizeof(struct hashTableNode)); pcurrent_node = manager.pHead; for(int i=0;i<number;i++){ scanf("%d %d", &index, &value); /*检查index是否是新的*/ struct hashTableNode *pTestNode = manager.pHead; for(int j=0;j<manager.size;j++){ pTestNode = pTestNode->pNext; if(pTestNode->index == index){ isIndexNew = 0; pTestNode->value+=value; break; } } if(isIndexNew){ manager.size+=1; pcurrent_node->pNext = (struct hashTableNode*)malloc(sizeof(struct hashTableNode)); pcurrent_node = pcurrent_node->pNext; pcurrent_node->index = index; pcurrent_node->value = value; } isIndexNew = 1; } /*不按顺序循环输出哈希表*/ // pcurrent_node = manager.pHead; // for(int i=0;i<manager.size;i++){ // pcurrent_node = pcurrent_node->pNext; // printf("%d %d\n",pcurrent_node->index, pcurrent_node->value); // } /*加载index并排序*/ int *pIndex=(int*)malloc(manager.size*sizeof(int)); pcurrent_node = manager.pHead; /*加载*/ for(int i=0;i<manager.size;i++){ pcurrent_node = pcurrent_node->pNext; pIndex[i] = pcurrent_node->index; } /*排序*/ int temp; for(int i=0,min=0;i<manager.size;i++){ for(int j=i;j<manager.size;j++){ if(pIndex[i]>pIndex[j]){ temp=pIndex[i]; pIndex[i] = pIndex[j]; pIndex[j]=temp; } } } /*按从小到大输出*/ /*加载*/ for(int i=0;i<manager.size;i++){ /*查找并输出*/ pcurrent_node = manager.pHead; for(int j=0;i<manager.size;j++){ pcurrent_node = pcurrent_node->pNext; if(pIndex[i] == pcurrent_node->index){ printf("%d %d\n", pcurrent_node->index,pcurrent_node->value); break; } } } /*释放内存*/ struct hashTableNode *pDeleteNode; pcurrent_node = manager.pHead; for(int i=0;i<manager.size;i++){ pDeleteNode = pcurrent_node; pcurrent_node = pcurrent_node->pNext; free(pDeleteNode); } free(pIndex); return 0; }