Singly Linked List insertion

Singly Linked List insertion

inserting a node at the beginning of singly linked list

use code from the create and display nodes and getnode function to assign data click here

  1. create a function inserbeg( )
  2. create a *newnode pointer
  3. call getnode( ) function to assign data to newnode
Singly Linked List insertion at the beginning

4.initialize nexnode->next address to the head address

Singly Linked List insertion at the beginning

4 .intialize head to newnode pointer in the else block

Singly Linked List insertion at the beginning
newnode -> next = head;
head = newnode;

program for inserting a node at the beginning of singly linked list

void insertbeg()
{
node *newnode;
newnode = getnode();
if(head == NULL)
{
head = newnode;
}
else
{
newnode -> next = head;
head = newnode;
}
printf("node inserted successfully\n");
}

inserting a node at the ending of singly linked list

Singly Linked List insertion at the beginning

use code from the create and display nodes and getnode function to assign data click here

  1. create a function inserend( )
  2. create a newnode , temp pointer from sturcture NODE
  3. call getnode( ) function to assign data to newnode, intialize temp=head
Singly Linked List insertion at the beginning

4.move the temp pointer to every node to access every data by using while condition temp->next=NULL

change value of temp (to access next node) to temp=temp->next

Singly Linked List insertion at the beginning

5.after exiting while temp pointer will be at last node,now connect this last node with the newnode (temp->next=newnode)

Singly Linked List insertion at the beginning
temp = head;
while(temp -> next != NULL)
{
temp = temp -> next;
}
temp -> next = newnode;

Program for inserting a node at the ending of singly linked list

void insertend()
{
node *newnode, *temp;
newnode = getnode();
if(head == NULL)
{
head = newnode;
}
else
{
temp = head;
while(temp -> next != NULL)
{
temp = temp -> next;
}
temp -> next = newnode;
}
printf("node inserted successfully\n");
}

inserting a node at the middle of singly linked list

void insertchoice(int p)
{
int i;
node *newnode,*temp;
newnode = getnode();
temp = head;
if (newnode==NULL)
{
printf("Unable to allocate memory.");
}
else
{
for (i=2;i<=p-1;i++)
{
temp=temp->next;
if(temp==NULL)
{
break;
}
}
if(temp!=NULL)
{
newnode->next=temp->next;
temp->next=newnode;
printf("DATA INSERTED SUCCESSFULLY\n");
}
else
{
printf("UNABLE TO INSERT DATA AT THE GIVEN POSITION\n");
}
}
}
Last updated on by vishal devxo