w3resource

C++ Linked List Exercises: Delete first node of a Singly Linked List

C++ Linked List: Exercise-10 with Solution

Write a C++ program to delete first node of a given Singly Linked List.

Test Data:
Original Linked list:
13 11 9 7 5 3 1
Delete first node of Singly Linked List:
11 9 7 5 3 1

Sample Solution:

C++ Code:

#include <iostream>


using namespace std; 
//Declare node 
struct Node{
    int num;
    Node *next;
};
 
//Starting (Head) node
struct Node *head=NULL;
 
//Insert node at start
void insert_Node(int n){
    struct Node *new_node=new Node;
    new_node->num=n;
    new_node->next=head;
    head=new_node;
}

//Delete first node of the list
    void delete_first_node() 
	{
      if(head != NULL) {
        Node* temp = head;
        head = head->next; 
        free(temp); 
      }
    }

//Display all nodes
void display_all_nodes()
  {
	struct Node *temp = head;
    while(temp!=NULL){
        cout<<temp->num<<" ";
        temp=temp->next;
    }
    }
 
int main(){
    insert_Node(1);
    insert_Node(3);
    insert_Node(5);
    insert_Node(7);
    insert_Node(9);
    insert_Node(11);
    insert_Node(13);
    cout<<"Original Linked list:\n";
	display_all_nodes();
	cout<<"\n\nDelete first node of  Singly Linked List:\n";
    delete_first_node();
    display_all_nodes();
    cout<<endl;
    return 0;
}

Sample Output:

Original Linked list:
13 11 9 7 5 3 1 

Delete first node of  Singly Linked List:
11 9 7 5 3 1 

Flowchart:

Flowchart: Delete first node of a Singly Linked List.
Flowchart: Delete first node of a Singly Linked List.

CPP Code Editor:

Contribute your code and comments through Disqus.

Previous C++ Exercise: Insert a node at any position of a Singly Linked List.
Next C++ Exercise: Delete a middle node from a Singly Linked List.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.

C++ Programming: Tips of the Day

Why does the C++ map type argument require an empty constructor when using []?

This issue comes with operator[]. Quote from SGI documentation:

data_type&operator[](constkey_type& k) - Returns a reference to the object that is associated with a particular key. If the map does not already contain such an object, operator[] inserts the default object data_type().

If you don't have default constructor you can use insert/find functions. Following example works fine:

myMap.insert(std::map<int, MyClass>::value_type ( 1, MyClass(1) ) );
myMap.find( 1 )->second;

Ref: https://bit.ly/3PQBRJi

 





We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook