Untitled

Anonymous
plain_text
09/14/2026 8:47 AM
1.6 KB
17
Indexable
#include <iostream>
using namespace std;

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

int main() 
{
    int n;
    cout << "Number of elements: ";
    cin >> n;

    // INPUT

    // Step 1: Create the first node (head)
    Node* head = new Node();
    cout << "Enter element 1: ";
    cin >> head->data;
    head->next = nullptr; // End of list for now

    // Keep track of the last node created
    Node* tail = head;

    // Step 2: Create and link the remaining nodes
    for (int i = 2; i <= n; i++) 
    {
        // Allocate a new memory block
        Node* newNode = new Node();
        cout << "Enter element " << i << ": ";
        cin >> newNode->data;
        newNode->next = nullptr; // New node points to nothing yet
        // Attach the new node to the end of the list
        tail->next = newNode;
        // Move tail pointer to the new end node
        tail = newNode;
    }

    // OUTPUT

    cout << "\nLinked List:\n";
    
    // Start at the head and walk until we reach nullptr
    Node* p = head;
    while (p != nullptr)
    {
        cout << p->data << " -> ";
        p = p->next; // Move to the next node
    }
    cout << "NULL\n";

    return 0;
}
Editor is loading...
Leave a Comment