【问题标题】:Adding Nodes in Linked List在链表中添加节点
【发布时间】:2014-03-25 21:40:33
【问题描述】:

我正在尝试将用户添加到链接列表。我有两个结构和一个名为 add_friend 的添加方法,用于设置节点的添加。该程序不要求用户输入,而是通过 add_friend 方法中的参数传递信息:除了将节点(用户)添加到列表之外,我还必须检查用户是否已经存在。当我尝试比较字符串以查看用户是否存在时出现错误。有什么帮助吗?不幸的是 C 是我最弱的编程语言,我很难理解指针

struct UserAccountNode {
    struct UserAccount* content;
    char circle;
    struct UserAccountNode* next;

} *head = NULL;

struct UserAccount {
    char username[255];
    char lastnm [256];
    char firstnm[256];
    char password[256];
    char gender;
    int phone;
    struct Post* post_list;
    struct UserAccountNode* friend_list;
};

int add_friend(UserAccount* user, char Circle, UserAccount* Friend) {
    struct UserAccountNode* friend_list;

    friend_list = (struct UserAccountNode* ) malloc (sizeof(struct UserAccountNode));

    while (friend_list != NULL)
        if (stricmp(Circle, head->friend_list) == 0) {
            friend_list -> next = head;
            head = friend_list;
        } else { 
            printf("%d, User Already Exists", Friend);
        }

    return 0;
}

【问题讨论】:

  • 如果这是the dissection of this的后果,你需要放下StackOverflow,拿起你的课本。严重地。 停止编写代码,花点时间研究和阅读它。没有捷径可走。
  • 您想如何确定好友是否已在列表中?您可以检查是否已经存在具有相同地址的用户吗?

标签: c struct linked-list nodes


【解决方案1】:

代码不比较字符串。它将char - Circle - 与UserAccountNode*friend_list 进行比较。但是stricmp 要求两个参数都是const char *。您必须对 friend_list 中的所有项目进行循环,并将每个 username 与给定的项目进行比较。

另一个问题:您为UserAccountNode 分配内存,但没有为其内部字段UserAccount* content 分配内存。当您尝试读取数据时,它可能会导致应用程序崩溃。

【讨论】:

    【解决方案2】:

    Circle 的类型是 char 而不是 char*head->friend_list 的类型是 UserAccountNode*

    因此,您尝试在此处将非字符串对象作为字符串进行比较:

    if (stricmp(Circle, head->friend_list) == 0)

    我认为你的程序无法编译。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-10
      • 2022-01-07
      • 1970-01-01
      • 2020-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-26
      相关资源
      最近更新 更多