C++ Program to Delete the First Node in a given Singly Linked List

C++Server Side ProgrammingProgramming

A linked list is a linear data structure that has multiple nodes that are connected with each other. Each node consists of two fields – Data Field and the address of the next node.

Let us assume we have a singly linked list and we need to delete the first node from this linked list. For example,

Input 1 − 4 → 3 → 2 → 1

Output − 3 → 2 → 1 →

Explanation − ‘4’ is the first node in the given singly linked list. After deleting the first node, the linked list will be 3→2→1.

Input 2 − 1 → 2 → 3 →

Output − 2 → 3 →

Explanation − After deleting the first node ‘1’, the linked list will be 2 → 3.

Approach to solve this problem

Initially, we have a linked list that consists of nodes. Each node contains the data and address to the next node. After inserting the data in the linked list, we will create a function to delete the first node.

Thus, we will create a temporary pointer that initially points to the head and move the head to the next node. Now delete the temporary node and return the linked list.

  • A function deleteAthead(node*&head) takes the pointer to the head and deletes the first node of the linked list.

  • Create a temporary pointer that initially points to the head.

  • Head moves to the next node.

  • Delete the temporary pointer.

  • Return the linked list.

Example

#include<iostream>
using namespace std;
int main(){
class node{
   public:
      int data;
      node*next;
      node(int d){
         data=d;
         node*next=NULL;
      }
};
void insertAtFirstNode(node*&head, int data){
   node*n= new node(data);
   n->next= head;
   head=n;
}
void print(node*head){
   while(head!=NULL){
      cout<<head->data<<"->";
      head=head->next;
   }
   cout<<endl;
}
void deleteAtFirst(node*&head){
   if(head==NULL){
      return;
   }
   node*temp=head;
   head= head->next;
   delete temp;
   return;
}
int main(){
   node*head= NULL;
   insertAtFirstNode(head,1);
   insertAtFirstNode(head,2);
   insertAtFirstNode(head,3);
   insertAtFirstNode(head,4);
   deleteAtFirst(head);
   print(head);
}

Output

Running the above code will generate the output as,

3 → 2 → 1 →

Since the given singly linked list is 4 → 3 → 2 → 1 →, after deleting the first node which is 4, the linked list will become, 3 → 2 → 1 →

raja
Published on 05-Feb-2021 07:06:02
Advertisements