Deletion in singly linked list at the end

There are two scenarios in which, a node is deleted from the end of the linked list.

  1. There is only one node in the list and that needs to be deleted.
  2. There are more than one node in the list and the last node of the list will be deleted.

In the first scenario,

the condition head → next = NULL will survive and therefore, the only node head of the list will be assigned to null. This will be done by using the following statements.

In the second scenario,

The condition head → next = NULL would fail and therefore, we have to traverse the node in order to reach the last node of the list.

For this purpose, just declare a temporary pointer temp and assign it to head of the list. We also need to keep track of the second last node of the list. For this purpose, two pointers ptr and ptr1 will be used where ptr will point to the last node and ptr1 will point to the second last node of the list.

this all will be done by using the following statements.

Now, we just need to make the pointer ptr1 point to the NULL and the last node of the list that is pointed by ptr will become free. It will be done by using the following statements.

Algorithm

  • Step 1: IF HEAD = NULL
  • Write UNDERFLOW
       Go to Step 8
      [END OF IF]

  • Step 2: SET PTR = HEAD
  • Step 3: Repeat Steps 4 and 5 while PTR -> NEXT!= NULL
  • Step 4: SET PREPTR = PTR
  • Step 5: SET PTR = PTR -> NEXT
  • [END OF LOOP]

  • Step 6: SET PREPTR -> NEXT = NULL
  • Step 7: FREE PTR
  • Step 8: EXIT

DS Delete element from end

C Function :

Output

1.Append List
2.Delete node
3.Exit
4.Enter your choice?1

Enter the item
12

Node inserted

1.Append List
2.Delete node
3.Exit
4.Enter your choice?2

Only node of the list deleted ...

Next Topic#




Latest Courses