Singly Linked List deletion

delete first node from single linked list

Singly Linked List deletion

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

  1. create a function deletebeg( )
  2. create a *temp pointer from structure NODE,initialize temp with head
Singly Linked List deletion

3.move head to the next node using the address of next node (head=head->next)

Singly Linked List deletion

4.delete the temp node using the free keyword

Singly Linked List deletion

5.first node will be deleted

Singly Linked List deletion
temp = head;
head = temp -> next;
free(temp);
printf("\n Node deleted ");

code to delete first node from single linked list

void deletebeg()
{
node *temp;
if(head == NULL)
{
printf("\n No nodes are exist..");
return ;
}
else
{
temp = head;
head = temp -> next;
free(temp);
printf("\n Node deleted ");
}
}

delete last node from single linked list

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

Singly Linked List deletion
  1. create a function deleteend( )
  2. create a temp ,prev pointer from structure NODE
  3. initialize temp and prev with head pointer
Singly Linked List deletion

4.create a while loop with condition (temp->next!=NULL),

5.intitalize prev with temp and move temp pointer to next node using the next address field

6.we are using while loop to move prev pointer to the second element from the ending and temp pointer to the last node

Singly Linked List deletion

7.make the prev node’s next address field as NULL

8.delete last node(temp pointed node) using free keyword in c

Singly Linked List deletion

9.last node will be deleted

Singly Linked List deletion
temp = head;
prev = head;
while(temp -> next != NULL)
{
prev = temp;
temp = temp -> next;
}
prev -> next = NULL;
free(temp);

code to delete last node from single linked list

void deleteend()
{
node *temp, *prev;
if(head == NULL)
{
printf("\n Empty List..");
return ;
}
else
{
temp = head;
prev = head;
while(temp -> next != NULL)
{
prev = temp;
temp = temp -> next;
}
prev -> next = NULL;
free(temp);
printf("\n Node deleted ");
}
}
Last updated on by vishal devxo