tailDeletion.cpp
This is from the practice midterm.
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <iostream>
using namespace std;
class LList{
private:
struct node{
int data;
node* next;
};
node* head = nullptr;
node* current = nullptr;
public:
LList(){
}
LList(int a){
head = new node{a, nullptr};
}
void enqueue(int a){
node* tmp = nullptr;
if (head == nullptr){
head = new node{a, nullptr};
current = head;
}
else {
tmp = new node{a, nullptr};
current -> next = tmp;
current = current -> next;
}
}
void remove_last(){
node* prev = nullptr;
for (node* i = head; i != nullptr; i = i -> next){
if (i -> next == nullptr){
delete i;
prev -> next = nullptr;
return;
}
prev = i;
}
}
void print(){
cout << "Linked List Elements: ";
for (node* i = head; i != nullptr; i = i -> next){
cout << i -> data << " ";
}
cout << endl;
}
};
int main(){
LList program;
cout << "Add elements to the linked list: " << endl;
program.enqueue(4);
program.print();
program.enqueue(5);
program.print();
program.enqueue(9);
program.print();
cout << "Remove the last element inside the linked list: " << endl;
program.remove_last();
program.print();
return 0;
}
Console Output
1
2
3
4
5
6
Add elements to the linked list:
Linked List Elements: 4
Linked List Elements: 4 5
Linked List Elements: 4 5 9
Remove the last element inside the linked list:
Linked List Elements: 4 5