Deletion of head and tail element logic in a linked list using C language.

CServer Side ProgrammingProgramming

Linked lists use dynamic memory allocation i.e. they grow and shrink accordingly. It is collection of nodes.

Node has two parts, which are data and link. These are explained below.

Operations on linked lists

There are three types of operations on linked lists which are as follows −

  • Insertion
  • Deletion
  • Traversing

Deletion

  • Identify the node.
  • Adjust the links in such a way that deallocation of the nodes does not make the list as unconnected components.
  • Return/display element to delete.
  • Deallocate the memory.

Delete Head element

Follow the steps given below to delete a head element in C programming language.

1. void del_head()
2. {
3. int x;
   Node *temp;
4. if(Head==NULL)
5. {
6. printf("List is empty");
7. return;
8. }
9. x=Head->ele;
10. temp=Head;
11. if(Head==Tail)
12. Head=Tail=NULL:
13. Else
14. Head=Head->next;
15. printf("Deleted element %d",x);
16. free(temp);
17. }

Here,

Step 4 − Checks for list empty or not.

Step 9 − Reads an element to delete.

Step 10 − Head referred by temp pointer.

Step 11 − Checks for last deletion.

Step 14 − Move head pointer to next element in the list.

Step 15 − Displays element to delete.

Step 16 − Deallocate the memory.

Delete Tail element

Follow the steps given below to delete a tail element in C programming language.

1. void del_tail()
2. {
3. int x;
4. Node *temp;
5. if(Head==NULL)
6. {
7. printf("List is empty");
8. return;
9. }
10. temp=Head;
11. while(temp->next !=Tail)
12. temp=temp->next;
13. x=Tail->ele;
14. Tail=temp;
15. Temp=temp->next
16. Tail->next=NULL;
17. printf("Deleted element %d",x);
18. free(temp);
19. }

Here,

Step 4 − Checks for list empty.

Step 10, 11, 12 − Move the temp pointer to last but one node of the list.

Step 13 − Reads tail element to delete.

Step 14 − Moves tail pointer to last but one node.

Step 15 − Moves the temp pointer to last node of the list.

Step 16 − Removes the reference from tail node to temp node.

Step 17 − Displays elements to delete.

Step 18 − Deallocate the memory.

raja
Published on 25-Mar-2021 12:52:21
Advertisements