【问题标题】:Single linked list, self sorting based on *char input单链表,基于*char输入的自排序
【发布时间】:2023-03-21 13:10:01
【问题描述】:

我在这方面花费了大量时间,最后终于让它工作了(因为它保存了值并打印它们)。我想按字母顺序对它进行排序。如果我将值添加到我的列表中,它们不会以我添加它们的相同顺序打印出来,但它似乎有点随机......似乎 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("%s\n", top->nam);
    }else
    while (1){


        if (tmp->next == NULL){
            tmp->next = neww;
            break;
        }
        //printf("top - %s %d\n neww - %s %d\n 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 %d\n", 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;
}

【问题讨论】:

  • 1:什么语言? 2:问题是什么?
  • 也许您应该从了解strcpy 的实际工作原理开始。
  • 你在add_value中为tmp分配空间,然后立即覆盖指向那个空间的指针;我很确定这是不对的。
  • 我删除了 C++ 标签,因为代码是纯 C 的,但有一个例外,&lt;iostream&gt; 的未使用包含。我把它留在原地是因为人们应该非常警惕改变问题的实质。这是错的吗?
  • @Cheersandhth.-Alf:尽管有过时的习语,但如果代码是通过 C++ 编译器推送的(显然是这样),那么它就是 C++ ......这使得这是一个 C++ 问题。我已经把标签放回去了。

标签: c++ list sorting


【解决方案1】:

我发现了两件事似乎不对。

a) 这一行

list * tmp = (struct list*)malloc(sizeof(struct list));

错误(用于两个函数)。你需要一个指针——不是一个新元素——所以不需要malloc

b) 这段代码

    if (tmp->next == NULL){
        tmp->next = neww;
        break;
    }

当您到达最后一个元素时,似乎会变得活跃。但是,您仍然必须检查是否要在列表中已有的元素之前或之后插入新元素。您的代码总是将新元素放在后面。考虑一下您的列表只有 1 个元素的情况。

顺便说一句 - 如果你想编写 c++,你应该使用 std::string 而不是 c 风格的 char 数组。另外,请查看std::multimap,而不是您自己的链表。

【讨论】:

    猜你喜欢
    • 2023-03-08
    • 2011-11-22
    • 2020-06-13
    • 2018-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多