To implement a singly linked list in C++, we first define a Node
class that represents each individual node in the linked list. The Node
class contains two members: data
, which stores the value of the node, and next
, which is a pointer to the next node in the list.
TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4class Node {
5public:
6 int data;
7 Node* next;
8
9 Node(int data) {
10 this->data = data;
11 next = nullptr;
12 }
13};
Next, we define a SinglyLinkedList
class that contains a pointer to the head of the linked list. The SinglyLinkedList
class provides methods for inserting nodes into the list and printing the list.
TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4class SinglyLinkedList {
5public:
6 Node* head;
7
8 SinglyLinkedList() {
9 head = nullptr;
10 }
11
12 void insert(int data) {
13 Node* newNode = new Node(data);
14 if (head == nullptr) {
15 head = newNode;
16 } else {
17 Node* current = head;
18 while (current->next != nullptr) {
19 current = current->next;
20 }
21 current->next = newNode;
22 }
23 }
24
25 void printList() {
26 Node* current = head;
27 while (current != nullptr) {
28 cout << current->data << " ";
29 current = current->next;
30 }
31 }
32};
xxxxxxxxxx
52
}
using namespace std;
class Node {
public:
int data;
Node* next;
Node(int data) {
this->data = data;
next = nullptr;
}
};
class SinglyLinkedList {
public:
Node* head;
SinglyLinkedList() {
head = nullptr;
}
void insert(int data) {
Node* newNode = new Node(data);
if (head == nullptr) {
head = newNode;
} else {
Node* current = head;
while (current->next != nullptr) {
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment