Master LIFO and FIFO processing models
Section 2 of 8
Theoretical concepts are fine, but in software, we care about the logic. Behold the core functions that handle data entry and exit.
O(1) Time Complexity
Adds an element to the Top of the stack. If the stack is implemented with a fixed-size array and is full, this throws a Stack Overflow error.
1def push(stack, value): if isFull(): throw Overflow stack.top += 1 stack[top] = valueO(1) Time Complexity
Removes and returns the Top element. If you try to pop an empty stack, you get a Stack Underflow error.
1def pop(stack): if isEmpty(): throw Underflow value = stack[top] stack.top -= 1 return valueLIFO Visualization
Since we NEVER search the stack and ONLY interact with the very top, every operation is Constant Time O(1).
To keep our code clean, we use these standard helper functions to check the state of our stack before performing push/pop.
Returns the top element WITHOUT removing it. Useful for checking next steps.
Essential boolean checks that prevent Underflow/Overflow crashes.
1bool isEmpty() { return top == -1; } int peek() { return stack[top]; }