To insert a node at the front of a linked list, the operation involves creating a new node, linking it to the current head of the list, and updating the head to the newly created node. This process is efficient as it requires minimal adjustments to pointers.
Algorithm
- Create a new node with the given data.
- Point the next reference of the new node to the current head of the list.
- Update the head of the list to this new node.
Implementation in C++
#include <bits/stdc++.h>
using namespace std;
// Definition of the Node structure
struct Node {
int data; // Stores the data of the node
Node* next; // Pointer to the next node in the list
// Constructor to initialize the node
Node(int new_data) {
data = new_data;
next = nullptr;
}
};
// Function to insert a new node at the beginning of the linked list
Node* insertAtFront(Node* head, int new_data) {
// Create a new node with the given data
Node* new_node = new Node(new_data);
// Link the new node to the current head
new_node->next = head;
// Return the new node as the new head of the list
return new_node;
}
// Function to print the elements of the linked list
void printList(Node* head) {
Node* curr = head; // Start from the head of the list
// Traverse the list and print the data of each node
while (curr != nullptr) {
cout << " " << curr->data;
curr = curr->next;
}
cout << endl; // Newline at the end
}
// Main function
int main() {
// Creating a linked list with nodes 20 -> 30 -> 40 -> 50
Node* head = new Node(20);
head->next = new Node(30);
head->next->next = new Node(40);
head->next->next->next = new Node(50);
// Data for the new node
int data = 10;
// Insert the new node at the beginning of the list
head = insertAtFront(head, data);
// Print the updated linked list
printList(head);
return 0;
}