对如下的数据进行处处理,使得左边相同的字符串对应的右边的数累加,用链表实现.要求在构建链表过程中累加.
aas 3
sdd 2
aas 5
ase 1
sdr 4
输出:
aas 8
sdd 2
ase 1
sdr 4
当时上机(Linux)时程序输出两行就内存出错,找不到原因,
下面的是回来后写的
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct _Node {
char* str;
int num;
struct _Node* next;
}Node;
int Append(Node* head, Node* node)
{
Node* p = head;
Node* q = p;
if (p->next)
{
p = p->next;
while (p)
{
if (!strcmp(p->str,node->str) )
{
p->num += node->num;
return 0;
}
q = p;
p = p->next;
}
}
q->next = (Node*)malloc(sizeof(Node));
q = q->next;
q->str = (char*)malloc(strlen(node->str)+1);
strcpy(q->str, node->str);
q->num = node->num;
q->next = NULL;
return 0;
}
int Output(Node* head)
{
Node* p = head;
p = p->next;
while (p)
{
printf("%s %d/n", p->str, p->num);
p = p->next;
}
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
//if (argc<=1)
//{
// printf("Please Input File Name!/n");
// return -1;
//}
FILE* fp;
fp = fopen("E:/DotNet/cxTest/Debug/input.txt", "r");
int n = 0;
char line[100];
int len = 80;
char szData[32];
int nNum;
Node* head;
Node* temp;
head = (Node*)malloc(sizeof(Node));
temp = (Node*)malloc(sizeof(Node));
head->str = NULL;
head->num = 0;
head->next = NULL;
// while ((n=getline(&line, &len, fp)) != -1) // for Linux
while (fgets(line,100,fp) != NULL) // for ANSI C
{
sscanf(line, "%s%d", &szData, &nNum);
temp->str = (char*)malloc(strlen(szData)+1);
strcpy(temp->str, szData);
temp->num = nNum;
temp->next = NULL;
Append(head, temp);
}
Output(head);
return 0;
}