c - 头在单链表中不断获得与尾指针相同的值
问题描述
我正在尝试创建一个包含两个参数的节点的单链表。每当我使用尾指针将另一个节点排入队列时,头指针的值与新节点相同。
我确定指针指向相同的内存位置或类似的东西,但我不知道如何解决这个问题。
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;
}
我想使用这个函数来创建一个单链表,头节点指向列表中的第一个元素,尾节点指向列表中的最后一个元素。当前代码导致两个变量都代表最后添加的元素。
解决方案
这里有一些问题。首先,要解决您的问题,请将最后两行替换为:
tail = tail->next = newNode;
另外,考虑一下:
tail = tail->next;
tail = newNode;
如果您在下一条语句中重新分配相同的变量,那么将变量分配给一个值有什么意义?您之前也有同样的错误:
newNode->p = malloc(sizeof(struct process));
newNode->p = newProcess;
由于第二行,您使用第一行实现的唯一事情是内存泄漏。完全删除第一行。
推荐阅读
- python - 关于如何处理coco的测试数据集的问题
- javascript - aframe 分屏转单屏效果
- text - 将连字符字典批量导入 InDesign
- javascript - 如何使用 Puppeteer 执行 POST?
- javascript - 如何在角度的子子项中将编辑的值更改/返回为false
- r - 在 postResample 预测中返回 NA
- amazon-dynamodb - DynamoDb 使用 boto3 选择特定属性
- javascript - 如何在 Javascript 中从 JSON 文件中删除对象
- django - “静态”文件夹在生产中应具有哪些权限和所有权/
- manim - 我得到 sh: latex: command not found 尝试给 latex 和 manim 发短信时出现错误