﻿ C++ - Delete first node of a Singly Linked List

# 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:
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> // Including input-output stream header file

using namespace std; // Using standard namespace

// Declare a structure for defining a Node
struct Node {
int num; // Data field to store a number
Node *next; // Pointer to the next node
};

struct Node *head = NULL; // Starting (Head) node initialized as NULL

// Function to insert a node at the start of the linked list
void insert_Node(int n) {
struct Node *new_node = new Node; // Creating a new node
new_node->num = n; // Assigning data to the new node
new_node->next = head; // Pointing the new node to the current head
}

// Function to delete the first node of the list
void delete_first_node() {
if (head != NULL) { // Check if the list is not empty
free(temp); // Free the memory of the original head node
}
}

// Function to display all nodes in the linked list
void display_all_nodes() {
struct Node *temp = head; // Temporary pointer to traverse the list
while (temp != NULL) { // Loop through all nodes until the end is reached
cout << temp->num << " "; // Displaying the data in the current node
temp = temp->next; // Move to the next node
}
}

int main() {
insert_Node(1); // Inserting a node with value 1
insert_Node(3); // Inserting a node with value 3
insert_Node(5); // Inserting a node with value 5
insert_Node(7); // Inserting a node with value 7
insert_Node(9); // Inserting a node with value 9
insert_Node(11); // Inserting a node with value 11
insert_Node(13); // Inserting a node with value 13

cout << "Original Linked list:\n"; // Displaying message for the original list
display_all_nodes(); // Displaying all nodes in the original list

cout << "\n\nDelete first node of Singly Linked List:\n"; // Displaying message for the deletion
delete_first_node(); // Deleting the first node of the list
display_all_nodes(); // Displaying all nodes after deletion

cout << endl; // Displaying newline
return 0; // Returning from the main function
}
``````

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:

CPP Code Editor: