C++ Linked List Creation and Display: A Step-by-Step Guide
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:
- Node Structure: The
Nodestruct defines the building block of the linked list. Each node stores data (data) and a pointer to the next node (next). - insert Function: This function inserts a new node with the given
datainto the linked list. It handles both cases: an empty list and a non-empty list. - display Function: This function traverses the linked list from the
headand prints the data of each node. - 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
原文地址: https://www.cveoy.top/t/topic/mJfN 著作权归作者所有。请勿转载和采集!