Hi! Hope you're enjoying this blog. I have a new home at www.goldsborough.me. Be sure to also check by there for new posts <3

Monday, January 6, 2014

Pushing back in a Linked List in C++

The way one usually adds elements in a linked list, setting the new struct's pointer to the head and the head to the new struct, is somewhat like the push_front() method of a vector. I quickly tried out what it would be like to have a push_back function. Ta. Da.

Assuming a struct Node with an int num attribute. If this is too little context for you check out my basic tutorial on linked lists, where I have an actual program and you can see what does what: Linked Lists in C++


Node* Back(Node* head, int num) //returns the new first head
{
    Node* new_node = new Node; //get new node
    Node* last; //the node before the current node during iteration
    Node* init = head; //the initial node, used when the head hasn't been changed

    new_node->num = num; //set the attribute
    new_node->next_node = NULL; //since this will be the new last node, set to NULL 

    if (head == NULL) return new_node; //we need different behaviour if this is the first node, head is just the new node
    else
    {
        while (head != NULL) //iterate, we need the node before last since head will in the end be NULL
            {
                last = head; //current node
                head = head->next_node; //next node
            }

        last->next_node = new_node; //set the previous last node to the new last node
        return init; //return the inital head
    
}

Just a snippety snippet here, summing up my Linked Lists tutorials.

No comments :

Post a Comment