Singly linked list

A simple linked list is a set of elements (also called nodes) connected by pointers. The first element is often called the root element. The pointers provide navigation to the next element. Since there is only one pointer per node, the list can only be traversed in one direction. Typical operations that can be applied to a list are creating the root node, deleting a node, appending a node, or deleting the entire list.

#include <iostream>
#include <stack>
using namespace std;

class Node {
public:
    int data;
    Node *next;
};

void displayNodes(Node *node) {
    while (node != NULL) {
        cout << node->data << " ";
        node = node->next;
    }
}

int main() {
    Node *first = NULL;
    Node *second = NULL;
    Node *third = NULL;

    first = new Node();
    second = new Node();
    third = new Node();

    first->data = 2;
    first->next = second;

    second->data = 4;
    second->next = third;

    third->data = 6;
    third->next = NULL;

    displayNodes(first);

    return 0;
}
Output
2 4 6

Inserting Nodes

#include <iostream>
#include <stack>
using namespace std;

class Node {
public:
    int data;
    Node *next;
};

void push(Node **head, int nodeData) {
    Node *newNode = new Node;

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

void displayNodes(Node *node) {
    while (node != NULL) {
        cout << node->data << " ";
        node = node->next;
    }
}

int main() {
    Node *head = NULL;

    push(&head, 7);
    push(&head, 8);
    push(&head, 9);

    displayNodes(head);

    return 0;
}
Output
9, 8, 7

Deleting Nodes

#include <iostream>
#include <stack>
using namespace std;

class Node {
public:
    int data;
    Node *next;
};

void push(Node **head, int nodeData) {
    Node *newNode = new Node;

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

void deleteFirstNode(Node **head) {
    Node *tempNode = *head;

    if (head != NULL) {
        *head = tempNode->next;
        delete tempNode;
        return;
    }
}

void displayNodes(Node *node) {
    while (node != NULL) {
        cout << node->data << " ";
        node = node->next;
    }
}

int main() {
    Node *head = NULL;

    push(&head, 7);
    push(&head, 8);
    push(&head, 9);

    deleteFirstNode(&head);

    displayNodes(head);

    return 0;
}
Output
8 7