C++ Linked List Creation and Display

This C++ program demonstrates how to create and display a simple linked list.

Code:

#include <iostream>
using namespace std;

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

void insert(Node*& head, int data) {
    Node* newNode = new Node;
    newNode->data = data;
    newNode->next = NULL;

    if (head == NULL) {
        head = newNode;
    }
    else {
        Node* temp = head;
        while (temp->next != NULL) {
            temp = temp->next;
        }
        temp->next = newNode;
    }
}

void display(Node* head) {
    Node* temp = head;
    while (temp != NULL) {
        cout << temp->data << ' ';
        temp = temp->next;
    }
}

int main() {
    Node* head = NULL;

    insert(head, 1);
    insert(head, 2);
    insert(head, 3);

    display(head);

    return 0;
}

Explanation:

  1. Node Structure: The Node struct defines the building block of the linked list. Each node stores data (data) and a pointer to the next node (next).
  2. insert Function: This function inserts a new node with the given data into the linked list. It handles both cases: an empty list and a non-empty list.
  3. display Function: This function traverses the linked list from the head and prints the data of each node.
  4. main Function: Here, we create an empty list (head = NULL), insert three nodes with values 1, 2, and 3, and then display the contents of the list.

Output:

1 2 3
C++ Linked List Creation and Display: A Step-by-Step Guide

原文地址: https://www.cveoy.top/t/topic/mJfN 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录