In this section, we will cover the fundamental operations associated with stacks. Stacks are a type of data structure that follows the Last In, First Out (LIFO) principle. This means that the last element added to the stack will be the first one to be removed. The basic operations that can be performed on a stack are:

  1. Push: Add an element to the top of the stack.
  2. Pop: Remove the top element from the stack.
  3. Peek (or Top): Retrieve the top element of the stack without removing it.
  4. isEmpty: Check if the stack is empty.
  5. Size: Get the number of elements in the stack.

Let's explore each of these operations in detail with examples and code snippets.

  1. Push Operation

The push operation adds an element to the top of the stack.

Example

Imagine a stack of books. When you add a new book on top, you are performing a push operation.

Code Snippet (Python)

class Stack:
    def __init__(self):
        self.items = []

    def push(self, item):
        self.items.append(item)
        print(f"Pushed {item} to stack")

# Usage
stack = Stack()
stack.push(10)
stack.push(20)
stack.push(30)

Explanation

  • We define a Stack class with an __init__ method to initialize an empty list items.
  • The push method appends the given item to the items list.
  • We create an instance of the Stack class and push three elements (10, 20, 30) onto the stack.

  1. Pop Operation

The pop operation removes the top element from the stack and returns it.

Example

Continuing with the stack of books, removing the top book is a pop operation.

Code Snippet (Python)

class Stack:
    def __init__(self):
        self.items = []

    def push(self, item):
        self.items.append(item)

    def pop(self):
        if not self.is_empty():
            return self.items.pop()
        else:
            return "Stack is empty"

    def is_empty(self):
        return len(self.items) == 0

# Usage
stack = Stack()
stack.push(10)
stack.push(20)
stack.push(30)
print(stack.pop())  # Output: 30
print(stack.pop())  # Output: 20

Explanation

  • The pop method removes and returns the last element from the items list if the stack is not empty.
  • The is_empty method checks if the stack is empty by returning True if the length of items is zero.
  • We push three elements onto the stack and then pop two elements, which returns 30 and 20, respectively.

  1. Peek (or Top) Operation

The peek operation retrieves the top element of the stack without removing it.

Example

Looking at the top book of the stack without removing it is a peek operation.

Code Snippet (Python)

class Stack:
    def __init__(self):
        self.items = []

    def push(self, item):
        self.items.append(item)

    def pop(self):
        if not self.is_empty():
            return self.items.pop()
        else:
            return "Stack is empty"

    def peek(self):
        if not self.is_empty():
            return self.items[-1]
        else:
            return "Stack is empty"

    def is_empty(self):
        return len(self.items) == 0

# Usage
stack = Stack()
stack.push(10)
stack.push(20)
stack.push(30)
print(stack.peek())  # Output: 30

Explanation

  • The peek method returns the last element of the items list without removing it if the stack is not empty.
  • We push three elements onto the stack and then peek at the top element, which returns 30.

  1. isEmpty Operation

The isEmpty operation checks if the stack is empty.

Example

Checking if there are any books in the stack is an isEmpty operation.

Code Snippet (Python)

class Stack:
    def __init__(self):
        self.items = []

    def is_empty(self):
        return len(self.items) == 0

# Usage
stack = Stack()
print(stack.is_empty())  # Output: True
stack.push(10)
print(stack.is_empty())  # Output: False

Explanation

  • The is_empty method returns True if the length of items is zero, indicating the stack is empty.
  • We create an instance of the Stack class, check if it is empty, push an element, and check again.

  1. Size Operation

The size operation returns the number of elements in the stack.

Example

Counting the number of books in the stack is a size operation.

Code Snippet (Python)

class Stack:
    def __init__(self):
        self.items = []

    def size(self):
        return len(self.items)

# Usage
stack = Stack()
stack.push(10)
stack.push(20)
stack.push(30)
print(stack.size())  # Output: 3

Explanation

  • The size method returns the length of the items list.
  • We push three elements onto the stack and then check the size, which returns 3.

Summary

In this section, we covered the basic operations that can be performed on a stack:

  • Push: Adding an element to the top of the stack.
  • Pop: Removing the top element from the stack.
  • Peek: Retrieving the top element without removing it.
  • isEmpty: Checking if the stack is empty.
  • Size: Getting the number of elements in the stack.

Understanding these operations is crucial for effectively using stacks in programming. In the next section, we will explore how to implement a stack from scratch.

© Copyright 2024. All rights reserved