Creating your first Linked List

In this tutorial we are going to learn how to create a linked list and print its contents.

Lets see the steps to solve this problem.

  • Create a node
  • Create a new node with data.
  • Insert the new node into the linked list.
  • Print the linked list.

Example:

Let's see the code-

#include <bits/stdc++.h>
using namespace std;

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

int main()
{
    Node *head = new Node();
    Node *a = new Node();
    Node *b = new Node();

    head->data = 20;
    a->data = 15;
    b->data = 10;

    head->next = a;
    a->next = b;
    b->next = NULL;


    //traversing
    Node *temp = head;
    while (temp != NULL)
    {
        cout << temp->data << ", ";
        temp = temp->next;
    }
    return 0;
}

Output:

If you run the above code, then you will get the following result.

20, 15, 10,

Conclusion:

This is how you create a simple linked list and print its contents. If you have any queries in the tutorial, please write them down in comment section.