我在这方面花费了大量时间,我终于让它完全工作了(因为它保存了值并打印了它们)。我想按字母顺序对它进行排序。如果我将值添加到我的列表中,它们不会按照我添加它们的相同顺序打印出来,但这似乎有点随机......似乎 strcpy 并没有按照我想象的方式工作......
#include <iostream>
#include <cstdlib>
#include <string.h>
#include <stdio.h>
using namespace std;
typedef struct list list_t;
struct list{
list *next;
char *nam;
int age;
};
static list_t *top = NULL;
void add_value(char * name1, int age){
list * neww = (list_t*)malloc(sizeof( list_t));
//tmp = top;
neww->age = age;
neww->nam = (char*)malloc(strlen(name1) + 1);
neww->next = NULL;
strcpy(neww->nam, name1);
list * tmp = (list_t*)malloc(sizeof(list_t));
tmp = top;
if (tmp==NULL){
top = neww;
//printf("%sn", top->nam);
}else
while (1){
if (tmp->next == NULL){
tmp->next = neww;
break;
}
//printf("top - %s %dn neww - %s %dn tmp - %s %d", top->nam, top->age, neww->nam, neww->age, tmp->nam, tmp->age);
if (strcmp(neww->nam, tmp->nam)>=0){
neww->next = tmp->next;
tmp->next = neww;
break;
}
tmp = tmp->next;
}
}
void print(){
list * tmp = (struct list*)malloc(sizeof(struct list));
tmp = top;
while (tmp){
printf("%s %dn", tmp->nam, tmp->age);
tmp = tmp->next;
}
}
int main(){
char namee[100];
int age;
for (int i = 0; i < 5; i++){
scanf("%s %d", &namee, &age);
add_value(namee, age);
}
print();
return 0;
}
我发现了两件看起来不对劲的事情。
a) 此行
list * tmp = (struct list*)malloc(sizeof(struct list));
错误(用于两个函数)。你需要一个指针 - 而不是一个新元素 - 所以不需要malloc
.
b) 此代码
if (tmp->next == NULL){
tmp->next = neww;
break;
}
当您到达最后一个元素时,似乎会变得活跃。但是,您仍必须检查新元素是要在列表中已有的元素之前还是之后插入。代码始终将新元素放在后面。考虑一下您的列表只有 1 个元素的情况。
顺便说一句 - 如果你想写 c++,你应该使用 std::string
而不是 c 风格的字符数组。另外,请查看std::multimap
而不是您自己的链表。