how to create a node in c++ code example

Example 1: linkedlist implementation in c++

#include <iostream>

using namespace std;

struct node
{
    int data;
    node *next;
};

class linked_list
{
private:
    node *head,*tail;
public:
    linked_list()
    {
        head = NULL;
        tail = NULL;
    }

    void add_node(int n)
    {
        node *tmp = new node;
        tmp->data = n;
        tmp->next = NULL;

        if(head == NULL)
        {
            head = tmp;
            tail = tmp;
        }
        else
        {
            tail->next = tmp;
            tail = tail->next;
        }
    }
};

int main()
{
    linked_list a;
    a.add_node(1);
    a.add_node(2);
    return 0;
}

Example 2: how to use a new node c++

struct node(){
  int key; 
  node *next;
  node(x){  
    key = x;
    next = NULL;     
}}
// after you take a input of a linked list .
// creating a new node.
node *temp = new node(key);  // tem pointer pointing towards the new node. 
temp -> next = head; // inserting the mew node in the start .

Tags:

Cpp Example