Reversing a Linked List | A Helpful Line-by-Line Code Tutorial

A code tutorial on how to reverse a linked list.

#include <stdio.h>
#include <stdlib.h>

typedef struct Node * nodePtr;

struct Node{

    int data;
    nodePtr next;

};

nodePtr globalHead;

static void reverse(nodePtr *head_ref){

    nodePtr prev   = NULL;
    nodePtr current = *head_ref;
    nodePtr next = NULL;

    while (current != NULL)
    {
        next  = current->next;
        current->next = prev;
        prev = current;
        current = next;
    }

    *head_ref = prev;

}

void push(nodePtr *head, int data){

    nodePtr newNode = (nodePtr) malloc(sizeof(struct Node));
    newNode->data = data;
    newNode->next = NULL;

    if ((*head) == NULL){
        *head = newNode;
        globalHead = *head;
    }else{
        (*head)->next = newNode;
        *head = newNode;
    }

}

void printList(nodePtr head){

    nodePtr current = head;
    while(current != NULL){
        printf("%d -> ",current->data);
        current = current->next;
    }
    printf("\n");

}

// *head = head in the main function,
// it is only there to connect the two and
// not let make the function return anything
// passed by reference
// globalHead points to the start of the linked list
// if you are passing the address over here you have to
// make a double pointer over there in the function

int main(void)
{
    nodePtr head = NULL;

    // linked list is formed from top to bottom fashion
    // push is done in constant time O(1)

    push(&head, 4); // |
    push(&head, 3); // |
    push(&head, 1); // |
    push(&head, 5); // |
    push(&head, 7); // V

    printList(globalHead);

    reverse(&globalHead);

    printList(globalHead);

    return 0;
}