Home > Mobile >  How to write a linked list properly?
How to write a linked list properly?

Time:11-05

I will use push to push a string word in queue q and instead of keeping the pointer to the array, it will keeps a COPY of the word inside the queue.

This is my code.

struct node_struct {
    char *data;
    struct node_struct *next;
};

typedef struct node_struct Node;

struct queue_struct {
    Node *head, *tail;
};

typedef struct queue_struct Queue;
void push(Queue **q, char *word) 
{
    // q hasn't been allocated
    if (*q == NULL) {
        (*q) = malloc(sizeof(Queue));
    }

    Node *temp;
    temp = malloc(sizeof(Node));
    temp->data = word;
    temp->next = NULL;

    if ((*q)->head == NULL) {
        (*q)->head = (*q)->tail = temp;
    }
    else {
        (*q)->head->tail = temp;
        (*q)->head = temp;
    }
}

But it has a problem in this line (*q)->head->tail = temp;

It says struct "node_struct" has no field "tail". Does anyone know why this thing occurs and how to fix this?

CodePudding user response:

You are confusing the queue with the node. The queue has a head and a tail, but the node has a next pointer. You should be setting (*q)->tail->next = temp; instead.

  • Related