Jun 24, 2024
top variable to keep track of the top elementclass Stack {
int capacity;
int* array;
int top;
public:
Stack(int cap) {
capacity = cap;
array = new int[capacity];
top = -1;
}
void push(int element) {
if (top == capacity - 1) throw overflow_error("Stack Overflow");
array[++top] = element;
}
int pop() {
if (top == -1) throw underflow_error("Stack Underflow");
return array[top--];
}
bool isEmpty() { return top == -1; }
bool isFull() { return top == capacity - 1; }
int size() { return top + 1; }
int getTop() {
if (top == -1) throw underflow_error("Stack is Empty");
return array[top];
}
};
struct Node {
int data;
Node* next;
Node(int val) : data(val), next(nullptr) {}
};
void push(int element) {
Node* newNode = new Node(element);
newNode->next = head;
head = newNode;
}
int pop() {
if (!head) throw underflow_error("Stack is Empty");
int topVal = head->data;
Node* temp = head;
head = head->next;
delete temp;
return topVal;
}
isEmpty(): Checks if head is nullptrsize(): Traverse through nodes to count elementspush, pop, top, empty, size#include <stack>
std::stack<int> s;
s.push(10);
s.push(20);
int top = s.top(); // Access the top element
s.pop(); // Remove the top element
void copyStack(std::stack<int>& src, std::stack<int>& dest) {
std::stack<int> temp;
while (!src.empty()) {
temp.push(src.top());
src.pop();
}
while (!temp.empty()) {
dest.push(temp.top());
temp.pop();
}
}
void insertAtBottom(std::stack<int>& s, int element) {
if (s.empty()) {
s.push(element);
} else {
int topElement = s.top();
s.pop();
insertAtBottom(s, element);
s.push(topElement);
}
}
void reverseStack(std::stack<int>& s) {
if (s.empty()) return;
int topElement = s.top();
s.pop();
reverseStack(s);
insertAtBottom(s, topElement);
}