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