Stacks Data Structures
Stacks Data Structures
Mam Iram
Table of content
• Introduction
• Array based Implementation
• Creating stack
• Operations (Push, Pop, Top, Is Empty)
• Resizing stack
• Time and space complexity
• Implementation of stacks (pre -fix, in -fix, post -
fix)
• Time and space complexity
Stacks Data Structure
Key Features:
– LIFO: Last-in, first-out order of operations.
– Operations are restricted to one end of the stack
called the top.
Applications: Reversing strings
• Expression evaluation and conversion (prefix,
infix, postfix)
• Function call management in recursion
• Undo operations in text editors
2. Array-Based Implementation
class Stack {
private:
int *arr; // Pointer to dynamically allocate array
int capacity; // Maximum size of the stack
int top; // Index of the top element
public:
// Constructor
Stack(int size) {
capacity = size;
arr = new int[capacity];
top = -1;
}
// Destructor
~Stack() {
delete[] arr;
}
// Stack operations
void push(int value);
int pop();
int peek();
bool isEmpty();
void resize();
4. Operations
Push
Adds an element to the top of the
stack.
Example:
Example:
void Stack::push(int value) {
if (top == capacity - 1)
{
resize(); // Resize if the stack is full
}
arr[++top] = value; // Increment top and insert value
}
Pop
Push:
Time: O(1) for normal insertion; O(n) if resizing is needed.
Space: O(1) for normal insertion; O(n) additional space if resizing.
Pop:
Time: O(1)
Space: O(1)
Peek (Top):
Time: O(1)
Space: O(1)
Resizing:
Time: O(n) due to copying elements.
Space: O(n) additional space for a new array.
6. Implementation of Prefix, Infix, and Postfix
int main() {
string infix = "(A+B)*(C-D)";
cout << "Postfix: " << infixToPostfix(infix) << endl;
return 0;
}
7. Summary