In a linked list, each element is called a node. Each node consists of two parts: the data and a reference (also called a pointer) to the next node.
Here's an example of a simple linked list implemented using C++:
TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4int main() {
5 // Linked List implementation
6
7 // Node structure
8 struct Node {
9 int data;
10 Node* next;
11 };
12
13 // Create nodes
14 Node* node1 = new Node;
15 Node* node2 = new Node;
16 Node* node3 = new Node;
17
18 // Assign data values
19 node1->data = 1;
20 node2->data = 2;
21 node3->data = 3;
22
23 // Connect nodes
24 node1->next = node2;
25 node2->next = node3;
26 node3->next = nullptr;
27
28 // Traversal
29 Node* current = node1;
30 while (current != nullptr) {
31 cout << current->data << ' ';
32 current = current->next;
33 }
34
35 return 0;
36}
In this example, the linked list contains three nodes: node1
, node2
, and node3
. Each node is assigned a data value (1, 2, or 3) and a reference to the next node. The nullptr
value indicates the end of the list.
To traverse the linked list, we start from the first node (node1
) and print the data value. Then, we move to the next node using the reference (next
) until we reach the end of the list.
xxxxxxxxxx
36
}
using namespace std;
int main() {
// Linked List implementation
// Node structure
struct Node {
int data;
Node* next;
};
// Create nodes
Node* node1 = new Node;
Node* node2 = new Node;
Node* node3 = new Node;
// Assign data values
node1->data = 1;
node2->data = 2;
node3->data = 3;
// Connect nodes
node1->next = node2;
node2->next = node3;
node3->next = nullptr;
// Traversal
Node* current = node1;
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment