• Register
100 points
7 4

Inserting a node in a linked list can be done in two ways. First we can insert at the beginning and second we can insert at the end. But this article focuses on inserting nodes at the beginning of the linked list.

Approach

Assume we have a linked list with two nodes with values 2 and 3 respectively. Head pointer points us to the first node and we want to add a new node with value 1 at the beginning of the list. So, we’ll create a new node using a new operator and return its address into the pointer ptr. Let's say the address is 200. We want to store 1 in the data part of the node. Now we have to point the newly created node to the node containing value 2. To do this we can make use of the head pointer as the head pointer contains the address of the node containing the value 2, which is the beginning of our linked list. So we can use the statement ptr->link = head here we are copying the value of the head and the link part of the newly created node. Thus the link part contains the value 100 which is the address of the node containing value 2. Hence our newly created node is pointing to the node containing value 2. Now the last thing we have to do is point the head pointer to our newly created node as it will now be the beginning of the linked list. To do this we will use statement head = ptr which copies the value 200 to head which is the starting address of the newly created node thus head is pointing to the newly created node which is now the beginning of the linked list.
 

Program

#include <iostream>
using namespace std;

//Creating Node Structure
struct Node{
 int data;
 Node *link;
};
//creating head pointer and equating to NULL
Node *head=NULL;

//Function to insert at the beginning of linked list
void insertBeg (int d)
{
 Node *ptr = new Node();
 ptr->data=d;
 ptr->link=head;
 head=ptr;
}
//Function to insert at the end of linked list
void insertEnd (int d)
{
  Node *ptr = new Node();
  ptr->data=d;
  ptr->link=NULL;

  //If list is empty
  if(head==NULL)
  head=ptr;
  //else list is not empty
  else
  {
   Node *temp = head;
   while(temp->link != NULL)
   {
    temp=temp->link;
   }
   temp->link=ptr;

  }

}
//Function to display linked list
void dispLink()
{
 Node *temp=head;
 while(temp!=NULL)
 {
  cout<<temp->data<<" ";
  temp=temp->link;
 }
 cout<<"\n";
}
//Main Function
int main()
{
 insertBeg(2);
 insertBeg(1);
 insertEnd(3);
 dispLink();
 return 0;
}

Hope this will help.

100 points
7 4