-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLINK01P03.cpp
More file actions
63 lines (52 loc) · 1.36 KB
/
LINK01P03.cpp
File metadata and controls
63 lines (52 loc) · 1.36 KB
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
63
#include <iostream>
using namespace std;
class Node {
public:
int value;
Node* next;
// Constructor to initialize the node with a given value
Node(int val): value(val), next(nullptr) {}
};
class LinkedList {
public:
Node* head;
void insertAtEnd(int value) {
// Create a new Node with inital value as value
Node* newNode = new Node(value);
Node* current = head;
// If there are no nodes in the linked list
// Set the new node as head and return
if (head == NULL) {
head = newNode;
return;
}
// Iterate to the end of list
while (current -> next != NULL) {
current = current -> next;
}
// Set the next of last value to the new Node
current -> next = newNode;
}
int getLastValue() {
if (head == NULL) {
return -1;
} else {
Node* current = head;
while (current -> next != NULL) {
current = current -> next;
}
return current -> value;
}
}
};
int main() {
int n;
cin >> n;
LinkedList* list = new LinkedList();
int x;
for (int i = 0; i < n; i++) {
cin >> x;
list -> insertAtEnd(x);
cout << list -> getLastValue() << ' ';
}
}