Worksheet 1.1
Worksheet 1.1
Code:
#include <iostream>
Node* top;
public:
Stack() : top(nullptr) {}
bool isEmpty() const {
return top == nullptr;
}
void pop() {
if (isEmpty()) {
std::cout << "Stack is empty. Cannot pop.\n";
return;
}
T topElement() const {
if (isEmpty()) {
std::cout << "Stack is empty. No top element.\n";
return T();
}
return top->data;
}
~Stack() {
while (!isEmpty()) {
pop();
}
}
};
int main() {
Stack<int> stack;
stack.push(10);
stack.push(20);
stack.push(30);
stack.pop();
std::cout << "Top element after pop: " << stack.topElement() << '\n';
return 0;
}
3. Result/Output
The time complexity of this code is:
• For push Operation: O(1)
• For pop Operation: O(1)
Learning Outcomes:
• Learnt to analyse of the stack is empty and underflows.
• Learnt to check if the stack if full and overflows.
• Learnt to perform push and pop operation.
• Learnt how to return the top element.