Generalized stack using C++
Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2019-10-01
Problem Statement
Design and implement a Generalized Stack in C++ that can store elements of any type and provide standard stack operations. The focus is on object-oriented design, modularity, and generic programming using templates.
✅ Functional Requirements
1.Core Stack Operations
•push(T element) → Adds an element to the top of the stack.
•pop() → Removes and returns the top element.
•peek() / top() → Returns the top element without removing it.
•isEmpty() → Checks if the stack is empty.
•size() → Returns the number of elements in the stack.
2.Generics Support
•Stack should be type-agnostic using C++ templates.
•Should work with built-in types (int, double, char) and user-defined types (class objects).
3.Optional Enhancements
•Dynamic resizing of internal storage (array-backed stack).
•Support for linked-list based implementation to avoid fixed capacity.
•Exception handling for underflow (pop from empty stack) and overflow (if fixed size).
🔐 Constraints & Assumptions
•Stack operations should have O(1) time complexity ideally.
•Use C++ templates for generic type support.
•Memory management must be safe and leak-free (if dynamic allocation is used).
•Thread-safety is optional unless specified.
🧱 Key Components & Classes
1.Template Stack Class
1
2template <typename T>
3class GeneralizedStack {
4private:
5 vector<T> elements; // or dynamic array / linked list
6public:
7 void push(const T& element);
8 T pop();
9 T top() const;
10 bool isEmpty() const;
11 int size() const;
12};1.Internal Storage Options
•Vector / Dynamic Array → Easy resizing, contiguous memory.
•Linked List → Avoids resizing, supports unlimited stack size.
🔄 Example Workflow
1.Create stack: GeneralizedStack<int> stack;
2.stack.push(10); stack.push(20); → Stack now [10,20] (top = 20)
3.stack.top() → returns 20
4.stack.pop() → returns 20, stack now [10]
5.stack.isEmpty() → returns false
6.stack.pop(); stack.isEmpty() → returns true
🧪 Expected Deliverables
•Class diagram for GeneralizedStack<T> showing operations and storage.
•Implementation of push, pop, top, isEmpty, size.
•Test cases demonstrating:
•Stack with primitive types (int, double).
•Stack with user-defined objects.
•Handling empty stack (underflow).
•Optional: resizing for dynamic array implementation.
💡 Discussion Points
•Trade-offs: array-based vs linked-list-based stack.
•Memory management for generic types.
•Exception safety in pop() and top().
•Extensibility for additional features (e.g., min-stack, max-stack).