单链表,基于 *char 输入的自排序
Single linked list, self sorting based on *char input
我在这方面花费了大量时间,我终于让它完全工作了(因为它保存了值并打印了它们)。我想按字母顺序对它进行排序。如果我将值添加到我的列表中,它们不会按照我添加它们的相同顺序打印出来,但这似乎有点随机......似乎 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
而不是您自己的链表。
相关文章:
- 在 Arduino 上使用 sscanf 会导致与 const char * 不匹配,并且返回值始终相同,尽管输入值不同
- 在大小为 10 的 char 数组中输入超过 10 个字符的字符串并输出时,它会显示整个数组而不是前 10 个数组.为什
- 为什么当我尝试将char输入到int时,文件指针会卡住
- 程序的执行在 C++ 中输入 char 变量后结束
- 如果用户输入的输入大于 char 数组,则 cin.getline 会跳过输入提醒
- 当我将 char 数组发送到输入参数为字符串的函数时会发生什么?
- C++用用户输入在循环中填充 char 数组:输入整个字符串时到底发生了什么?
- 如何使用CIN将输入整数值获取到char类型变量中
- 输入重定向读取整数和char C
- C 读取输入,直到线char数组的结束
- std::cin 无法将命令行中的用户输入传递给具有 char 类型的变量吗?
- 接受类型char的输入的问题
- 将用户输入从int []转换为char [] []
- 使用RegQueryValueEx将reg_sz作为输入并将其用作char数组
- 仅将输入的第一个字符用于 char 变量
- 验证用户输入是否有效 [从 'char' 到 'char*' 的转换无效]
- C++:为什么为"int"变量输入"char"会导致递归变得疯狂?
- 将输入char*拆分为vector
- c++输入char类型,输出int类型
- 如何在等待用户输入int, float或其他类型时拒绝输入char/string