Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

`

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

(*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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading