Stack in Data Structures – Introduction, Operations & Examples

Stack in Data Structures

🚀 Introduction

A Stack is a linear data structure that follows the principle:

👉 LIFO (Last In, First Out)

This means:

  • The last element added is the first one to be removed.

🔹 Real-Life Example

Think of a stack of plates 🍽️:

  • You place plates on top → Push
  • You remove plates from top → Pop

👉 You cannot remove from the middle.


🔹 Stack Structure

Top → [30]
[20]
[10]

🔹 Basic Operations in Stack

1️⃣ Push (Insert)

Adds an element to the top of the stack.

2️⃣ Pop (Remove)

Removes the top element.

3️⃣ Peek (Top)

Returns the top element without removing it.

4️⃣ isEmpty

Checks if stack is empty.


🔹 Stack Operations Example

Initial Stack:

[10, 20]

👉 Push(30)

[10, 20, 30]

👉 Pop()

[10, 20]

🧑‍💻 PHP Implementation (Using Array)

<?phpclass Stack {
private $stack = []; // Push
public function push($value) {
array_push($this->stack, $value);
} // Pop
public function pop() {
if (empty($this->stack)) {
return "Stack Underflow";
}
return array_pop($this->stack);
} // Peek
public function peek() {
if (empty($this->stack)) {
return "Stack is Empty";
}
return end($this->stack);
} // isEmpty
public function isEmpty() {
return empty($this->stack);
} // Display
public function display() {
print_r($this->stack);
}
}// Example
$stack = new Stack();
$stack->push(10);
$stack->push(20);
$stack->push(30);echo "Top: " . $stack->peek() . "\n";
echo "Popped: " . $stack->pop() . "\n";$stack->display();?>

⚡ Time Complexity

OperationComplexity
PushO(1)
PopO(1)
PeekO(1)

🎯 Advantages

✅ Simple and easy to implement
✅ Efficient operations (O(1))
✅ Useful in recursion and backtracking


❌ Disadvantages

❌ Limited access (only top element)
❌ Cannot search efficiently


🧠 Real-World Applications

  • Function call stack (recursion)
  • Undo/Redo operations
  • Expression evaluation
  • Browser history

🧠 Interview Tips

👉 Common questions:

  • Implement stack using array/linked list
  • Valid parentheses problem
  • Next greater element
  • Min stack

🏁 Conclusion

Stack is one of the most important data structures in DSA.

👉 It is widely used in:

  • Algorithms
  • System design
  • Real-world applications
No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *