#include <iostream>
class Node {
public:
int data {};
Node* next {};
Node(int d = 0, Node* n = nullptr) : data(d), next(n) {}
};
Node* head {};
void push(int newData) {
head = new Node(newData, head);
}
int pop() {
if (!head) {
std::cout << "Stack Underflow.\n";
return -1;
}
constauto temp { head };
constauto tempVal { temp->data };
head = head->next;
delete temp;
return tempVal;
}
void Top() {
if (!head)
std::cout << "Stack is Empty.\n";
else
std::cout << "Top of Stack: " << head->data << '\n';
}
void printStack() {
std::cout << "The stack elements are : ";
for (auto temp {head}; temp; temp = temp->next)
std::cout << temp->data << ' ';
std::cout << '\n';
}
void clear() {
while (head) {
constauto tmp { head->next };
delete head;
head = tmp;
}
}
int main() {
push(1);
std::cout << "After the first PUSH ";
Top();
push(5);
std::cout << "After the second PUSH ";
Top();
printStack();
pop();
std::cout << "After the first POP operation ";
Top();
pop();
std::cout << "After the second POP operation ";
Top();
clear();
}
After the first PUSH Top of Stack: 1
After the second PUSH Top of Stack: 5
The stack elements are : 5 1
After the first POP operation Top of Stack: 1
After the second POP operation Stack is Empty.
Yeah - using a stack class is much better. I just updated the code using the existing methodology which only had a public class (could have been struct) for the node...
but why create your own linked-list (unless this is part of the exercise)? Why not use the standard library list? Based upon the original code (not using a class), then consider: