Docsity

C++ Stack Implementation: A Practical Guide, Lecture notes of Object Oriented Programming

Toggle sidebar
bg1
#include <iostream>
#define SIZE 5
using namespace std;
class STACK {
private:
int num[SIZE];
int top;
public:
STACK(); // Default constructor
int push(int);
int pop();
int isEmpty();
int isFull();
void displayItems();
};
// Constructor definition
STACK::STACK() {
top = -1;
}
// Check if stack is empty
int STACK::isEmpty() {
return (top == -1);
}
// Check if stack is full
int STACK::isFull() {
return (top == (SIZE - 1));
}
// Push operation
int STACK::push(int n) {
if (isFull()) {
return -1; // Indicate stack is full
}
num[++top] = n;
return n;
}
// Pop operation
int STACK::pop() {
if (isEmpty()) {
return -1; // Indicate stack is empty
}
return num[top--];
}
// Display stack contents
pf2

Partial preview of the text

Download C++ Stack Implementation: A Practical Guide and more Lecture notes Object Oriented Programming in PDF only on Docsity!

#include #define SIZE 5 using namespace std; class STACK { private: int num[SIZE]; int top; public: STACK(); // Default constructor int push(int); int pop(); int isEmpty(); int isFull(); void displayItems(); }; // Constructor definition STACK::STACK() { top = -1; } // Check if stack is empty int STACK::isEmpty() { return (top == -1); } // Check if stack is full int STACK::isFull() { return (top == (SIZE - 1)); } // Push operation int STACK::push(int n) { if (isFull()) { return -1; // Indicate stack is full } num[++top] = n; return n; } // Pop operation int STACK::pop() { if (isEmpty()) { return -1; // Indicate stack is empty } return num[top--]; } // Display stack contents

void STACK::displayItems() { cout << "STACK is: "; for (int i = top; i >= 0; i--) cout << num[i] << " "; cout << endl; } int main() { STACK stk; int choice, n, temp; do { cout << "\n0 - Exit." << endl; cout << "1 - Push Item." << endl; cout << "2 - Pop Item." << endl; cout << "3 - Display Items (Print STACK)." << endl; cout << "Enter your choice: "; cin >> choice; switch (choice) { case 0: break; case 1: cout << "Enter item to insert: "; cin >> n; temp = stk.push(n); if (temp == -1) cout << "STACK is FULL." << endl; else cout << temp << " inserted." << endl; break; case 2: temp = stk.pop(); if (temp == -1) cout << "STACK IS EMPTY." << endl; else cout << temp << " is removed (popped)." << endl; break; case 3: stk.displayItems(); break; default: cout << "An Invalid choice." << endl; } } while (choice != 0); return 0; }