Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

C++ Program to Implement Singly Linked List



A singly linked list is a type of data structure where each item (called a node) has two parts: the data and a link to the next node in the list. You start from the first node (called the head) and keep going until the link is empty (NULL).

For example, let's understand with this list of numbers:

9 -> 2 -> 7 -> 1 -> 3 -> NULL

In this case, the node containing 9 is the head, and the node containing 3 is the last node (its next pointer is NULL).

In this article, we will show how to implement a simple singly linked list in C++, covering basic operations like insertion at the beginning, end, and at a specific index, along with displaying the entire list.

Implementation of Singly Linked List

Below is a program that shows how to implement a singly linked list.

Step 1: Define the Node Structure

We start by defining a structure for the Node. Each node will hold an integer (data) and a pointer to the next node.

#include <iostream>
using namespace std;

// Declare head as a global variable
struct Node* head = NULL;  // Initialize the head of the list as NULL

struct Node {
   int data;           // Data part of the node
   struct Node* next;  // Pointer to the next node
};

Step 2: Insert a Node

We can insert nodes at three different positions in a singly linked list:

Insert at the Beginning

We will insert a new node at the beginning of the list. To do this we:

  • Created a new node with the given data.
  • Set the new node's next pointer to the current head.
  • Update the head to point to the new node.
Inserting at the starting
void insert(int new_data) {
   struct Node* new_node = new Node();  // Create a new node
   new_node->data = new_data;           // Assign data to the node
   new_node->next = head;               // Set the new node's next to current head
   head = new_node;                     // Move the head to point to the new node
}

Inserting a Node at a Specific Position

To insert a node at a specific position in the linked list, we need to follow these steps:

  • Create the new node.
  • Traverse the list to find the node before the desired position.
  • Make the previous node's next pointer point to the new node, and the new node's next pointer point to the node that was previously at that position.
inserting at specific index
void insertAtSpecificPosition(int new_data, int position) {
   struct Node* new_node = new Node();  // Create a new node
   struct Node* temp = head;            // Start from the head
   new_node->data = new_data;           // Set data for the new node
   new_node->next = NULL;               // Set next to NULL
   
   // Insert at the beginning if position is 0
   if (position == 0) {
      new_node->next = head;
      head = new_node;
      return;
   }
   
   // Traverse to the node before the desired position
   for (int i = 0; temp != NULL && i < position - 1; i++) {
      temp = temp->next;
   }
   
   // If position is out of bounds
   if (temp == NULL) {
      cout << "Position out of bounds." << endl;
      return;
   }
   
   // Insert the new node at the given position
   new_node->next = temp->next;
   temp->next = new_node;
}

Insertion at the End

To insert a node at the end of the list, we need to:

  • Create a new node.
  • Traverse the list to reach the last node.
  • Make the last node's next pointer point to the new node.
inserting at the end
void insertAtEnd(int new_data) {
   struct Node* new_node = new Node();  // Create a new node
   struct Node* temp = head;            // Start from the head
   new_node->data = new_data;           // Set data for the new node
   new_node->next = NULL;               // Set next to NULL (end of list)
   
   // If the list is empty, make the new node the head
   if (head == NULL) {
      head = new_node;
      return;
   }
   
   // Traverse to the last node
   while (temp->next != NULL) {
      temp = temp->next;
   }
   
   // Insert the new node at the end
   temp->next = new_node;
}

Step 3: Displaying the List

To display the contents of the linked list, we start from the head and traverse through each node, printing its data until we reach the end (NULL).

void display() {
struct Node* ptr = head;  // Pointer to the head of the list
while (ptr != NULL) {      // Traverse until the end of the list
    cout << ptr->data << " ";  // Print the data of the node
    ptr = ptr->next;           // Move to the next node
}
cout << endl;  // Print a newline at the end
}

Step 4: Testing the Singly Linked List

Finally, we write the main() function to test our singly linked list implementation.

int main() {
   struct Node* head = NULL;  // Initialize an empty linked list
   // Inserting elements into the linked list
   insert(6);
   insert(5);
   insert(4);
   insert(3);
   insert(2);
   insert(1);

   cout << "Initial list: ";
   display();  // Initially, the list is empty

   insert(7);
   cout << "List after insertion at the beginning: ";
   display();  // Display the linked list after inserting at the beginning
   
   return 0;
}

Complete Code

Here is the complete code to implement a singly linked list with all three insertion operations including inserting at the beginning, at a specific position, and at the end.

#include <iostream>
using namespace std;

// Define Node structure
struct Node {
   int data;
   struct Node* next;
};

// Initialize head pointer as NULL
struct Node* head = NULL;

// Insert a node at the beginning
void insert(int new_data) {
   struct Node* new_node = new Node();  // Create a new node using dynamic memory
   new_node->data = new_data;           // Set data for the new node
   new_node->next = head;               // Set the new node's next pointer to current head
   head = new_node;                     // Update head to point to the new node
}

// Insert a node at a specific position
void insertAtSpecificPosition(int new_data, int position) {
   struct Node* new_node = new Node();  // Create a new node
   struct Node* temp = head;            // Start from the head
   new_node->data = new_data;           // Set data for the new node
   new_node->next = NULL;               // Set next to NULL

   // If position is 0, insert at the beginning
   if (position == 0) {
      new_node->next = head;
      head = new_node;
      return;
   }

   // Traverse to the node before the desired position
   for (int i = 0; temp != NULL && i < position - 1; i++) {
      temp = temp->next;
   }

   // If position is out of bounds
   if (temp == NULL) {
      cout << "Position out of bounds." << endl;
      return;
   }

   // Insert the new node at the given position
   new_node->next = temp->next;
   temp->next = new_node;
}

// Insert a node at the end
void insertAtEnd(int new_data) {
   struct Node* new_node = new Node();  // Create a new node
   struct Node* temp = head;            // Start from the head
   new_node->data = new_data;           // Set data for the new node
   new_node->next = NULL;               // Set next to NULL (end of list)

   // If the list is empty, make the new node the head
   if (head == NULL) {
      head = new_node;
      return;
   }

   // Traverse to the last node
   while (temp->next != NULL) {
      temp = temp->next;
   }

   // Insert the new node at the end
   temp->next = new_node;
}

// Display the linked list
void display() {
   struct Node* ptr = head;  // Start from the head
   if (ptr == NULL) {
      cout << "The list is empty." << endl;
      return;
   }
   cout << "The linked list is: ";
   while (ptr != NULL) {  // Traverse until the end of the list
      cout << ptr->data << " ";
      ptr = ptr->next;
   }
   cout << endl;
}

int main() {
   // Insert nodes at the beginning
   insert(3);
   cout << "After inserting 3 at the beginning: ";
   display();
   
   insert(1);
   cout << "After inserting 1 at the beginning: ";
   display();
   
   insert(7);
   cout << "After inserting 7 at the beginning: ";
   display();
   
   insert(2);
   cout << "After inserting 2 at the beginning: ";
   display();
   
   insert(9);
   cout << "After inserting 9 at the beginning: ";
   display();
   
   // Insert a node at a specific position
   insertAtSpecificPosition(5, 2); // Insert 5 at position 2
   cout << "After inserting 5 at position 2: ";
   display();
   
   // Insert a node at the end
   insertAtEnd(10);
   cout << "After inserting 10 at the end: ";
   display();
   
   return 0;
}

Output:

Below is the output of the above program:

After inserting 3 at the beginning: The linked list is: 3
After inserting 1 at the beginning: The linked list is: 1 3
After inserting 7 at the beginning: The linked list is: 7 1 3
After inserting 2 at the beginning: The linked list is: 2 7 1 3
After inserting 9 at the beginning: The linked list is: 9 2 7 1 3
After inserting 5 at position 2: The linked list is: 9 2 5 7 1 3
After inserting 10 at the end: The linked list is: 9 2 5 7 1 3 10

Conclusion

In this article, we created a singly linked list in C++ and showed how to add nodes at the beginning, a specific position, and the end. These basic operations are key to working with linked lists. By updating the list as needed, we can manage and organize data easily.

Updated on: 2025-01-30T14:41:59+05:30

87K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements