c-使用void函数在循环链表的开头插入节点



我正试图使用void函数在循环链表的开头插入一个节点。当我在函数中将指针传递给指针头时,因为我必须更改指针头本身,它在第24行给我带来了一些错误,我在那里用注释标记了它:";错误就在这里";。在将指针传递给指针之前,它在末尾插入元素这是完整的代码:

#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
};
void circularLLTraversal(struct Node *head)
{
struct Node *ptr = head;
do
{
printf("Element: %dn", ptr->data);
ptr = ptr->next;
} while (ptr != head);
}
void insertionAtBeginning(struct Node **head, int data)
{
struct Node *ptr = (struct Node *)malloc(sizeof(struct Node));
ptr->data = data;
struct Node *p = *head->next; //The error is here
while (p->next != *head)
{
p = p->next;
}
// At this point p points to the last node of the circular linked list
p->next = ptr;
ptr->next = *head;
*head = ptr;
}
int main()
{
struct Node *head;
struct Node *second;
struct Node *third;
struct Node *fourth;
head = (struct Node *)malloc(sizeof(struct Node));
second = (struct Node *)malloc(sizeof(struct Node));
third = (struct Node *)malloc(sizeof(struct Node));
fourth = (struct Node *)malloc(sizeof(struct Node));
head->data = 4;
head->next = second;
second->data = 3;
second->next = third;
third->data = 6;
third->next = fourth;
fourth->data = 1;
fourth->next = head;
printf("Circular Linked List before insertion: n");
circularLLTraversal(head);
insertionAtBeginning(&head, 8);
printf("Circular Linked List after insertion: n");
circularLLTraversal(head);
return 0;
}

请告诉我指针对指针的错在哪里,这真的让我头疼。

您需要将*head用括号括起来以解决问题(*head(->下一个

请参阅以下链接:https://gcc.gnu.org/bugzilla/show_bug.cgi?id=91134#:~:text=%20修复%20编程%20侧%20是%20课程的%20只是%20包装%20*服务器%20在%20括号中%20但是%20错误%20消息%20应该%20仍然%20被%20修改%20imho。

代码是

void insertionAtBeginning(struct Node **head, int data)
{
struct Node *ptr = (struct Node *)malloc(sizeof(struct Node));
ptr->data = data;
struct Node *p = (*head)->next; // Fix
while (p->next != *head)
{
p = p->next;
}
// At this point p points to the last node of the circular linked list
p->next = ptr;
ptr->next = *head;
*head = ptr;
}

这可能是由于的优先顺序

最新更新