135. Compile-Time Fixed Stack

In safety-critical firmware, dynamic memory allocation (heap) is often forbidden due to fragmentation risks. Data structures like stacks and queues must have their maximum size fixed at compile-time to ensure deterministic memory usage.

Your task is to implement a Class Template named StaticStack. It must accept two template parameters:

  1. typename T: The type of data to store.
  2. int Capacity: The maximum number of elements (Non-Type Template Parameter).

The class must encapsulate a raw array T data[Capacity] and a top_index. Implement the following methods:

  • void push(T val): Add element. If full, print "Stack Overflow" and ignore.
  • void pop(): Remove top element. If empty, print "Stack Underflow" and ignore.
  • T peek(): Return top element. If empty, return 0 (or default construct T()) and print nothing (error handling logic varies, but for this exercise, assume safe usage or check empty first).
  • bool isEmpty(): Returns true if empty.

Program Flow:

  1. The main function (provided) instantiates a StaticStack<int, 3> (Capacity = 3).
  2. Read integer N (number of commands).
  3. Loop N times.
  4. Read string command.
    • If "PUSH", read integer val and call push(val).
    • If "POP", call pop().
    • If "PEEK", print the result of peek().
    • If "EMPTY", print "Yes" or "No".

Input Format:

  • First line: Integer N.
  • Next N lines: Command string, followed by val only if command is "PUSH".
  • Input provided via stdin.

Output Format:

  • PUSH: No output (unless overflow).
  • POP: No output (unless underflow).
  • PEEK: Print Top: <value>.
  • EMPTY: Print Empty: Yes or Empty: No.
  • Errors: Print Stack Overflow or Stack Underflow exactly.

Example: 

Example 1

Input:

6
PUSH 10
PUSH 20
PUSH 30
PUSH 40
PEEK
POP

Output:

Stack Overflow
Top: 30

(Explanation: Stack size is 3. Pushing 10, 20, 30 fills it. Pushing 40 triggers Overflow. Peek shows 30. Pop removes 30.)

Constraints:

  • N range: 1 to 20
  • Test logic uses int, but class must be a template.
  • Capacity is fixed at 3 for the test cases.
  • No std::vector or new/malloc.

 

 

 

Loading...

Input

6 PUSH 10 PUSH 20 PUSH 30 PUSH 40 PEEK POP

Expected Output

Stack Overflow Top: 30