-
Notifications
You must be signed in to change notification settings - Fork 0
/
constructor.cpp
62 lines (54 loc) · 1.32 KB
/
constructor.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>
using namespace std;
// Node class for the elements in the linked list
class Node {
public:
int data;
Node* next;
Node(int data) {
this->data = data;
this->next = nullptr;
}
};
// LinkedList class with methods to manipulate the linked list
class LinkedList {
public:
Node* head;
// Constructor to initialize the linked list
LinkedList() {
this->head = nullptr;
}
// Method to append elements to the linked list
void append(int data) {
Node* new_node = new Node(data);
if (!this->head) {
this->head = new_node;
return;
}
Node* last_node = this->head;
while (last_node->next) {
last_node = last_node->next;
}
last_node->next = new_node;
}
// Method to display the elements of the linked list
void display() {
Node* current = this->head;
while (current) {
cout << current->data << " ";
current = current->next;
}
}
};
// Example usage of the LinkedList class
int main() {
// Creating a LinkedList object
LinkedList ll;
// Appending elements to the linked list
ll.append(1);
ll.append(2);
ll.append(3);
// Displaying the elements of the linked list
ll.display();
return 0;
}