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

Example

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;	
};

void insertAtBeginning(LL**head,int dataToBeInserted)
{
	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
			*head=curr;
		
	else //make the next of the current node point to the present head and make the current node as the new head
		{
			curr->next=*head;
			*head=curr;
		}
		
		//O(1) constant time
}


void display(LL**head)
{
	LL*temp=*head;
	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
	insertAtBeginning(&head,6);
	insertAtBeginning(&head,16);
	insertAtBeginning(&head,15);
	insertAtBeginning(&head,50);
	insertAtBeginning(&head,1);
	insertAtBeginning(&head,23);

	
	cout<<"\nCurrent List is :-\n";
	display(&head);
	
	return 0;
}
Try It


Next > < Prev
Scroll to Top