Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

c++ linked list

#include <iostream>
using namespace std;

struct node
{
    int data;   // data of the node
    node *next; // pointer to the next node
};

node *head = NULL; // head is the pointer to the first node

void insertNode(int value)
{
    node *newNode, *last;  // newNode is the new node to be inserted and last is the last node of the list
    newNode = new node;    // newNode is creating a new node
    newNode->data = value; // newNode's data is set to the value passed to the function
    newNode->next = NULL;  // newNode's next is set to NULL

    if (head == NULL) // if the head (the pointer to the first node)is NULL
    {
        head = newNode;       // head is set to newNode
        newNode->next = NULL; // newNode's next is set to NULL to indicate that it is the last node
    }
    else
    {
        last = head;               // last is set to the head to start the search from the first node
        while (last->next != NULL) // while last's next is not NULL
        {
            last->next; // last is set to the next node
        }
        last->next = newNode; // last's next is set to newNode by pointing it to the new node
        newNode->next = NULL; // newNode's next is set to NULL to indicate that it is the last node
    }
}

int main()
{
    insertNode(5);  // inserting the first node
    insertNode(6);  // inserting the second node
    insertNode(7);  // inserting the third node
    insertNode(8);  // inserting the fourth node
    insertNode(9);  // inserting the fifth node
    insertNode(10); // inserting the last node
    return 0;
}
 
PREVIOUS NEXT
Tagged: #linked #list
ADD COMMENT
Topic
Name
2+1 =