Reputation: 43
I m trying to insert a node at the beginning of a circular linked list using a void function. When i pass pointer to pointer head in the function because i have to change the head itself, it is throwing me some error on line 24 where i marked it with comment : "the error is here". Before passing a pointer to pointer, it was inserting the element at the end Here's the complete code :
#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: %d\n", 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;
}
Please let me know where m i wrong with pointer to pointer, this really makes me scratch my head.
Upvotes: 0
Views: 116
Reputation: 133
You need to wrap the *head with parenthesis to fix the issue (*head)->next
refer the following link :https://gcc.gnu.org/bugzilla/show_bug.cgi?id=91134#:~:text=The%20fix%20programming%20side%20is%20of%20course%20just%20wrapping%20*server%20in%20parentheses%20but%20the%20error%20message%20should%20still%20be%20amended%20imho.
The code is
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;
}
It could be due the priority order
Upvotes: 1