0
votes

I'm trying to create a singly linked list with nodes containing two parameters. Whenever I enqueue another node using the tail pointer, the head pointer takes the same value as the new node.

I'm sure the pointers are pointing to the same memory location or something similar, but I'm not sure how to fix this.

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;
}

I'd like to use this function to be able to create a singly linked list with the head node pointing to the first element in the list and the tail node pointing to the last element in the list. The current code results in both variables representing the last element added.

2
` newNode->p = malloc(sizeof(struct process)); newNode->p = newProcess` leaks memory. tail = tail->next and where do you update the tail->next pointer value? - KamilCuk
Suggest searching stackoverflow.com for 'singly linked list' - user3629249

2 Answers

1
votes

Setting tail = tail->next is setting tail to null because it isn't set the first time around, and then both tail and head are immediately overwritten in the subsequent call.

1
votes

There are some issues here. First, to fix your problem, replace the two last lines with:

tail = tail->next = newNode;

Also, consider this:

tail = tail->next;
tail = newNode;

What is the point of assigning a variable to a value if you reassign the same variable in the next statement? You have the same error earlier on too:

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

Because of the second line, the only thing you achieve with the first line is a memory leak. Remove the first line completely.