Mark As Completed Discussion

In this lesson, we will explore the operations that can be performed on a linked list. Linked list operations include insertion, deletion, and searching for nodes in the list. These operations are essential for manipulating and managing linked lists in various applications.

Let's start with the insertion operation. To insert a node at the beginning of a linked list, we can follow these steps:

  1. Create a new node with the desired data.
  2. Set the next pointer of the new node to point to the current head of the linked list.
  3. Update the head pointer to point to the new node.

Here's an example of how the insertion operation can be implemented in C++:

TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4// Node structure for linked list
5struct Node {
6    int data;
7    Node* next;
8};
9
10// Function to insert a node at the beginning of the linked list
11void insertAtBeginning(Node** head, int newData) {
12    // Create a new node
13    Node* newNode = new Node;
14
15    // Assign data to the new node
16    newNode->data = newData;
17
18    // Set the next pointer of the new node to the current head
19    newNode->next = *head;
20
21    // Update the head to point to the new node
22    *head = newNode;
23}
24
25int main() {
26    // Initialize an empty linked list
27    Node* head = nullptr;
28
29    // Insert nodes at the beginning of the linked list
30    insertAtBeginning(&head, 3);
31    insertAtBeginning(&head, 2);
32    insertAtBeginning(&head, 1);
33
34    // Print the linked list
35    Node* temp = head;
36    while (temp != nullptr) {
37        cout << temp->data << " ";
38        temp = temp->next;
39    }
40    cout << endl;
41
42    return 0;
43}
CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment