Home > Enterprise >  Why is my linked list adding nodes to the beginning of the list rather than the end?
Why is my linked list adding nodes to the beginning of the list rather than the end?

Time:11-05

Why is this linked list adding nodes to the beginning and how can I change it to add them to the end of the list?

`

    struct Node 
    {
        void *function;
        void *caller;
        void *framePointer;
        void *stackFrameBeginningAddress;
        void *stackFrameEndingAddress;
        long startTime;
        long finishTime;
        struct Node *next;
    };

    void push(struct Node** head, void *function, void *caller, void *framePointer, void            *stackBegin, void *stackEnd, long start)
    {
        struct Node* newNode = (struct Node*) malloc(sizeof(struct Node));
        newNode->next = NULL;

        newNode->function = function;
        newNode->caller = caller;
        newNode->framePointer = framePointer;
        newNode->stackFrameBeginningAddress = stackBegin;
        newNode->stackFrameEndingAddress = stackEnd;
        newNode->startTime = start;

        newNode->next = (*head);
        (*head) = newNode;
    }

`

I have tried adding the node to the end using a while loop, but then face segmentation faults. I believe the problem might lie in memory allocation?

CodePudding user response:

(*head) = newNode; means you are updating the head. If you want to update the tail you either need to keep track of it:

(*tail)->next = malloc(sizeof(struct Node));
*tail = (*tail)->next;

Possible moving both the head and tail pointers to a struct LinkedList. Then you only update the head when it's the first node, i.e.:

if(!*head) {
   *head = *tail;
}

Another less great option is to walk the list starting at the head to find the tail before each insert.

  • Related