Welcome to the world of Linked Lists!
In this lesson, we will dive into implementing a linked list class and performing basic operations like insertion and deletion.
To get started, let's create a Node
class that will represent each element of the linked list. Each node will contain a data value and a pointer to the next node.
TEXT/X-C++SRC
1#include <iostream>
2
3class Node {
4public:
5 int data;
6 Node* next;
7
8 Node(int value) {
9 data = value;
10 next = nullptr;
11 }
12};
13
14int main() {
15 // Create Nodes
16 Node* node1 = new Node(1);
17 Node* node2 = new Node(2);
18 Node* node3 = new Node(3);
19
20 // Link Nodes
21 node1->next = node2;
22 node2->next = node3;
23
24 // Print Linked List
25 Node* current = node1;
26 while (current != nullptr) {
27 std::cout << current->data << " ";
28 current = current->next;
29 }
30 std::cout << std::endl;
31
32 return 0;
33}
xxxxxxxxxx
33
}
class Node {
public:
int data;
Node* next;
Node(int value) {
data = value;
next = nullptr;
}
};
int main() {
// Create Nodes
Node* node1 = new Node(1);
Node* node2 = new Node(2);
Node* node3 = new Node(3);
// Link Nodes
node1->next = node2;
node2->next = node3;
// Print Linked List
Node* current = node1;
while (current != nullptr) {
std::cout << current->data << " ";
current = current->next;
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment