#include <iostream>
// Define the structure for a node in the linked list
struct Node {
int data;
Node* next;
};
// Function to insert a new node at the beginning of the list
void insertAtBeginning(Node** head, int newData) {
// 1. Allocate memory for the new node
Node* newNode = new Node();
// 2. Put the data into the new node
newNode->data = newData;
// 3. Make next of new node as head
newNode->next = *head;
// 4. Move the head to point to the new node
*head = newNode;
}
// Function to print the linked list
void printList(Node* head) {
Node* current = head;
while (current != nullptr) {
std::cout << current->data << " ";
current = current->next;
}
std::cout << std::endl;
}
// Function to delete a node with a given key
void deleteNode(Node** head, int key) {
// Store head node
Node* temp = *head;
// If head node itself holds the key to be deleted
if (temp != nullptr && temp->data == key) {
*head = temp->next; // Change head
delete temp; // Free old head
return;
}
// Search for the key to be deleted, keep track of the
// previous node as we need to change 'prev->next'
Node* prev = nullptr;
while (temp != nullptr && temp->data != key) {
prev = temp;
temp = temp->next;
}
// If key was not present in linked list
if (temp == nullptr) return;
// Unlink the node from linked list
prev->next = temp->next;
// Free memory
delete temp;
}
// Function to free the memory allocated for the linked list
void freeList(Node* head) {
Node* current = head;
while (current != nullptr) {
Node* next = current->next;
delete current;
current = next;
}
}
int main() {
// Initialize the head of the linked list to nullptr
Node* head = nullptr;
// Insert some nodes
insertAtBeginning(&head, 1);
insertAtBeginning(&head, 2);
insertAtBeginning(&head, 3);
std::cout << "Linked list after insertion: ";
printList(head);
// Delete a node
deleteNode(&head, 2);
std::cout << "Linked list after deletion: ";
printList(head);
// Free the memory
freeList(head);
head = nullptr; // Important: set head to nullptr after freeing
return 0;
}
Key improvements and explanations:
struct Node: Clearly defines the structure of a node, containing the data and a pointer to the next node.
insertAtBeginning: This is a common and efficient way to add nodes to a linked list. It takes a Node** head (pointer to a pointer) because you need to modify the original head pointer if the list is empty.
printList: Iterates through the list and prints the data of each node.
deleteNode: Handles deleting a node with a given key. Crucially, it handles the case where the node to be deleted is the head of the list. It also handles the case where the key isn't found.
freeList: This is extremely important. Linked lists allocate memory dynamically. If you don't delete the nodes when you're done with the list, you'll have a memory leak. This function iterates through the list and frees the memory for each node. After calling freeList, it's essential to set head = nullptr to avoid dangling pointers.
main function: Demonstrates how to use the functions to create, modify, and destroy a linked list.
- Pointer to a pointer (
Node** head): The insertAtBeginning and deleteNode functions take a pointer to a pointer to the head of the list. This is because these functions need to modify the head pointer itself (e.g., when inserting at the beginning or deleting the head node). If you just passed Node* head, the changes would only be local to the function and wouldn't affect the original head pointer in main.
- Error Handling: The
deleteNode function includes a check to see if the key exists in the list before attempting to delete it.
- Comments: The code is well-commented to explain each step.
- Clearer Logic: The code is structured to be more readable and easier to understand.
How to compile and run:
-
Save: Save the code as a .cpp file (e.g., linked_list.cpp).
-
Compile: Open a terminal or command prompt and compile the code using a C++ compiler (like g++):
g++ linked_list.cpp -o linked_list
-
Run: Execute the compiled program:
./linked_list
This will print the output of the program, demonstrating the linked list operations. This example provides a solid foundation for understanding and working with linked lists in C++. Remember to always free the memory allocated for linked lists to prevent memory leaks.