Topic 4

Stack

LIFO โ€” Last In, First Out

A stack is like a pile of plates. You can only add/remove from the top.

4 Operations:
โ€ข push(value) โ€” add to top
โ€ข pop() โ€” remove top
โ€ข peek() โ€” view top without removing
โ€ข display() โ€” print all (top to bottom)

Push order: 10, 20, 30

30โ† top
20
10

After pop() โ†’ returns 30

20โ† top
10
๐Ÿ“
Array: top = -1. Push: arr[++top]. Pop: arr[top--]
๐Ÿ“
LL: Push = insert at head. Pop = delete head. No overflow!
๐Ÿ“
isFull(): top == maxSize - 1 (array only!). LL has no isFull.
๐Ÿ“
Display: Array prints top โ†’ 0. LL traverses current โ†’ NULL.

Array Stack vs Linked List Stack

AspectArrayLinked List
SizeFixed (needs maxSize)Dynamic (grows as needed)
Overflowtop == maxSize-1No overflow possible
Top variableint top = -1Node* top = NULL
Pusharr[++top] = valuenewNode->next = top
Popreturn arr[top--]Save data, move top, delete
MemoryContiguous blockScattered nodes
Destructordelete[] arrLoop pop() until empty
#include <iostream>
using namespace std;

class Stack {
private:
    int* arr;
    int top;
    int maxSize;

public:
    // Constructor
    Stack(int size) {
        maxSize = size;
        arr = new int[maxSize];
        top = -1;
    }

    bool isEmpty() {
        return top == -1;
    }

    bool isFull() {
        return top == maxSize - 1;
    }

    // Push element
    void push(int value) {
        if (isFull()) {
            cout << "Stack Overflow!" << endl;
            return;
        }
        arr[++top] = value;
        cout << value << " pushed onto stack." << endl;
    }

    // Pop element
    int pop() {
        if (isEmpty()) {
            cout << "Stack Underflow!" << endl;
            return -1;
        }
        return arr[top--];
    }

    // Peek (top element)
    int peek() {
        if (isEmpty()) {
            cout << "Stack is empty!" << endl;
            return -1;
        }
        return arr[top];
    }

    // Display stack
    void display() {
        if (isEmpty()) {
            cout << "Stack is empty!" << endl;
            return;
        }
        cout << "Stack elements: ";
        for (int i = top; i >= 0; i--) {
            cout << arr[i] << " ";
        }
        cout << endl;
    }

    // Destructor
    ~Stack() {
        delete[] arr;
    }
};

int main() {
    Stack s(5);
    s.push(10);
    s.push(20);
    s.push(30);
    s.display();        // 30 20 10

    cout << "Top Element: " << s.peek() << endl;
    cout << "Popped: " << s.pop() << endl;
    s.display();        // 20 10

    return 0;
}