首页 > 解决方案 > 头在单链表中不断获得与尾指针相同的值

问题描述

我正在尝试创建一个包含两个参数的节点的单链表。每当我使用尾指针将另一个节点排入队列时,头指针的值与新节点相同。

我确定指针指向相同的内存位置或类似的东西,但我不知道如何解决这个问题。

struct node
{
    struct process *p;
    struct node *next;
}

struct node* head;
struct node* tail;

void enqueue(struct process* newProcess)
{
    struct node *newNode = malloc(sizeof(struct node));
    newNode->p = malloc(sizeof(struct process));
    newNode->p = newProcess);

    if(tail==NULL)
    {
        head = tail = newNode;
        return;
    }

    tail = tail->next;
    tail = newNode;
}

我想使用这个函数来创建一个单链表,头节点指向列表中的第一个元素,尾节点指向列表中的最后一个元素。当前代码导致两个变量都代表最后添加的元素。

标签: clinked-listsingly-linked-list

解决方案


这里有一些问题。首先,要解决您的问题,请将最后两行替换为:

tail = tail->next = newNode;

另外,考虑一下:

tail = tail->next;
tail = newNode;

如果您在下一条语句中重新分配相同的变量,那么将变量分配给一个值有什么意义?您之前也有同样的错误:

newNode->p = malloc(sizeof(struct process));
newNode->p = newProcess;

由于第二行,您使用第一行实现的唯一事情是内存泄漏。完全删除第一行。


推荐阅读