# Create a singly linked list

## Write a program to create a singly linked list

In the singly linked list, each node has only one pointer which points to the next node. The first node is known as head of the list and the last node points to Null. Below Algorithm shows how to insert a node at the begining of the linked list and display all the nodes in the linked list

## Algorithm

First, define a node in the linked list which contains data value and the pointer to the next node
Inserting a node in the begining of the linked list
1. Create  two nodes head and current, everytime insert the data in the current node.
2. If the list is empty then set the current formed node as the head of the list else,
3. make the next of the current node point to the present head and make the current node as the new head

### Display

1. Create a temparory node pointer which points to head of the list
2. Till the list ends ie, temp!=NULL
if the temp's next pointer is not equal to null, print the data in that node and stop.
else, print the data and move to the next node.

## C++ Program

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

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

{
LL*curr=new LL;
//make a new node with this data and next pointing to NULL
curr->data=dataToBeInserted;
curr->next=NULL;

if(*head==NULL) //if list is empty then set the current formed node as head of list

else //make the next of the current node point to the present head and make the current node as the new head
{
}

//O(1) constant time
}

{
while(temp!=NULL) //till the list ends (NULL marks ending of list)
{
if(temp->next!=NULL)
cout<<temp->data<<" ->";
else
cout<<temp->data;

temp=temp->next; //move to next node
}
//O(number of nodes)
cout<<endl;
}

int main()
{

LL *head = NULL; //initial list has no elements

cout<<"\nCurrent List is :-\n";

return 0;
}``````

Scroll to Top