c - 在结构中存储数据(链表)

标签 c list structure

大家好,我正在学习 C,有一些问题我无法解决。

首先,这是我的数据结构:

struct user_node {
 void *name;
 struct user_node *next;
 struct msg_node *msgnext;
};

struct msg_node {
 void *sender;
 void *receiver;
 void *title;
 void *content;
 struct msg_node *msgnext;
};
struct user_node *user_database = NULL;

这个想法是用户可能有一条或多条消息。

我可以创建和删除用户,但我在存储消息时遇到问题,例如这里:

此函数的目的是将 temp 作为消息放入我的数据结构中,供我们在消息本身中找到的给定用户。 (temp已经是msg_node,其中包含我从另一个函数获取的数据)

void sendMsg(struct msg_node* temp) {
//if list is empty
if (user_database == NULL) {
    printf("There aren't users on the system.\n\n");
    return;
}

struct user_node** ptr = &user_database;
while (*ptr) {
    if (strncmp((*ptr)->name, (temp)->receiver, strlen(temp-
>receiver)) == 0) {


        temp->msgnext = &user_database->msgnext;
        user_database->msgnext = temp;

        return;
    }
    ptr = &(*ptr)->next;
}
printf("User not found on the system\n\n");

return;
}

我知道代码是错误的,但从昨天开始我就一直在搞乱这个,我无法弄清楚,有人可以帮助我吗?

提前致谢

最佳答案

通过将新节点的 next 指针设置为链表的头部,然后将链表的头部设置为新节点,可以在链表的前面插入一个节点。当列表头为 NULL 时,这甚至适用于空列表。

您的理解几乎是正确的,但列表的头部是与当前用户关联的,而不是与用户列表的头部(即数据库中的第一个用户)关联的。

以下代码应该可以完成您想要的操作:

int sendMsg(struct msg_node *msg)
{
    struct user_node *user = user_database;

    if (user == NULL) {
        printf("There aren't users on the system.\n");
        return -1;
    }

    while (user) {
        if (strcmp(ptr->name, msg->receiver) == 0) {
            msg->msgnext = user->msgnext;
            user->msgnext = msg;

            return 0;
        }

        user = user->next;
    }

    printf("User '%s' not found on the system.\n", msg->receiver);

    return -1;
}

注释:

  • 我已将指针从相当不伦不类的 tempptr 重命名为更具描述性的 msguser.
  • 我已让函数返回成功代码:0 表示成功,-1 表示失败。
  • strncmp 将仅比较一定数量的字符。我已将其更改为 strcmp,以便用户 Paul 和 Pauline 被视为不同。
  • 不需要将遍历指针设置为指向节点的指针。该技术很有用,但仅当您想要插入或删除节点时才有效。在前面插入是一种特殊情况,您不需要它。 (并且您插入一条消息,而不是用户,因此如果您想将消息插入到前面以外的其他位置,您可以使用指向消息节点的指针迭代子列表。)

关于c - 在结构中存储数据(链表),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46864852/

相关文章:

c - K&R 第 5.11 节中的排序程序

python - 迭代列表的不同方法

WPF:多列列表框/ ListView ?

list - 合并 2 个元组列表并在元组中添加非唯一值的 Pythonic 方法是什么?

c - 为什么我收到 "statement with no effect"警告?

c++ - 四元数旋转不起作用

c - 在某些情况下,尝试从服务内修改注册表会失败?

c - 在 C 中迭代请求行

R日期内部整数存储有 "L"- 可以删除吗?

MySQL 结构::友谊