Use app×
QUIZARD
QUIZARD
JEE MAIN 2026 Crash Course
NEET 2026 Crash Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
199 views
in Information Technology by (178k points)
Discover the versatility of stack operations with our comprehensive guide. Learn about push, pop, peek, and more. Master essential stack data structure concepts for efficient programming. Explore practical examples and best practices. Start optimizing your code today!

Please log in or register to answer this question.

2 Answers

0 votes
by (178k points)

Different Types of Stack Operations

let's explore different types of stack operations with example code. We'll cover the following operations:

  1. Initialization
  2. Push
  3. Pop
  4. Peek
  5. Checking Empty
  6. Checking Full (optional, depending on the implementation)

Let's dive into each operation with detailed explanations and example code.

1. Initialization

Before performing any stack operation, you need to initialize the stack. This typically involves allocating memory for the stack and initializing variables such as top pointer.

Example Code:

class Stack:
    def __init__(self, max_size):
        self.max_size = max_size
        self.stack = []
        self.top = -1
 

2. Push

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

Example Code:

def push(self, item):
    if self.top == self.max_size - 1:
        print("Stack Overflow")
        return
    self.top += 1
    self.stack.append(item)
    print(f"Pushed {item} onto the stack")
 

3. Pop

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

Example Code:

def pop(self):
    if self.top == -1:
        print("Stack Underflow")
        return None
    item = self.stack.pop()
    self.top -= 1
    print(f"Popped {item} from the stack")
    return item
 

4. Peek

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

Example Code:

def peek(self):
    if self.top == -1:
        print("Stack is empty")
        return None
    return self.stack[self.top]
 

5. Checking Empty

This operation checks if the stack is empty.

Example Code:

def is_empty(self):
    return self.top == -1
 

6. Checking Full (optional)

For stack implementations with a maximum size, you may want to check if the stack is full.

Example Code:

def is_full(self):
    return self.top == self.max_size - 1
 

Putting it All Together

Here's how you can use these operations together:

Example:

stack = Stack(5)
stack.push(1)
stack.push(2)
stack.push(3)
print("Top element:", stack.peek())
stack.pop()
print("Top element after pop:", stack.peek())
print("Is stack empty?", stack.is_empty())
 

This will output:

Pushed 1 onto the stack
Pushed 2 onto the stack
Pushed 3 onto the stack
Top element: 3
Popped 3 from the stack
Top element after pop: 2
Is stack empty? False
 

These operations provide the basic functionality for working with a stack data structure. Depending on your requirements, you may extend these operations or implement additional functionalities.

0 votes
by (178k points)

FAQs on Different Types of Stack Operations

Q: What is a stack? 

A: A stack is a linear data structure that follows the Last In, First Out (LIFO) principle, where elements are inserted and removed from the same end called the top.

Q: What are the basic operations of a stack? 

A: Basic stack operations include:

  • Push: Adds an element to the top of the stack.
  • Pop: Removes and returns the top element of the stack.
  • Peek (or Top): Returns the top element of the stack without removing it.
  • isEmpty: Checks if the stack is empty.
  • Size: Returns the number of elements in the stack.

Q: How are stack operations implemented? 

A: Stack operations can be implemented using arrays or linked lists. Arrays offer constant-time access but may require resizing if the stack grows beyond its initial capacity. Linked lists provide dynamic memory allocation but may have slightly higher overhead due to pointer manipulation.

Q: Can you provide an example of stack implementation using arrays in Python?

A: Here is the code.

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

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

    def pop(self):
        if not self.is_empty():
            return self.stack.pop()
        else:
            return None

    def peek(self):
        return self.stack[-1] if not self.is_empty() else None

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

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

# Example usage
stack = Stack()
stack.push(1)
stack.push(2)
print("Stack peek:", stack.peek())
print("Stack size:", stack.size())
print("Popped item:", stack.pop())
 

Q: What are some applications of stacks? 

A: Stacks are used in various applications, including:

  • Expression evaluation (e.g., infix to postfix conversion)
  • Function call management (e.g., maintaining function call stack in recursion)
  • Undo mechanisms in text editors
  • Backtracking algorithms
  • Parsing and syntax analysis in compilers

Q: How can I implement stack operations using a linked list in C++?

A: Here is the code.

#include <iostream>

using namespace std;

struct Node {
    int data;
    Node* next;
};

class Stack {
private:
    Node* top;

public:
    Stack() : top(nullptr) {}

    void push(int item) {
        Node* newNode = new Node();
        newNode->data = item;
        newNode->next = top;
        top = newNode;
    }

    int pop() {
        if (isEmpty()) {
            cout << "Stack underflow\n";
            return -1; // or throw an exception
        }
        int item = top->data;
        Node* temp = top;
        top = top->next;
        delete temp;
        return item;
    }

    int peek() {
        if (isEmpty()) {
            cout << "Stack is empty\n";
            return -1; // or throw an exception
        }
        return top->data;
    }

    bool isEmpty() {
        return top == nullptr;
    }
};

// Example usage
int main() {
    Stack stack;
    stack.push(1);
    stack.push(2);
    cout << "Stack peek: " << stack.peek() << endl;
    cout << "Popped item: " << stack.pop() << endl;
    return 0;
}
 

Q: Are there any stack libraries available in programming languages? 

A: Yes, many programming languages provide built-in stack data structures or libraries for stack operations. For instance, in Java, you can use the java.util.Stack class, and in C++, the Standard Template Library (STL) provides std::stack.

Important Interview Questions and Answers on Different Types of Stack Operations

Q: What is a stack?

A stack is a linear data structure that follows the Last In, First Out (LIFO) principle. It means that the element inserted last is the first one to be removed.

Q: How can you implement a stack?

A stack can be implemented using arrays or linked lists.

Q: Explain push and pop operations in a stack.

  • push(item): This operation adds an item to the top of the stack.
  • pop(): This operation removes and returns the item at the top of the stack.

Q: Write code for a stack using an array (in Python).

Here is the code.

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

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

    def pop(self):
        if not self.is_empty():
            return self.stack.pop()
        else:
            return None

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

    def peek(self):
        if not self.is_empty():
            return self.stack[-1]
        else:
            return None

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

Q: Explain peek operation in a stack.

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

Q: Write code to reverse a string using a stack.

Here is the code.

def reverse_string(string):
    stack = Stack()
    for char in string:
        stack.push(char)
    reversed_string = ""
    while not stack.is_empty():
        reversed_string += stack.pop()
    return reversed_string

# Example usage:
string = "hello"
print(reverse_string(string))  # Output: "olleh"
 

Q: Explain the application of stacks.

Stacks are used in applications such as expression evaluation, function call management (call stack), undo mechanisms in text editors, backtracking algorithms, and parsing algorithms.

Q: Write code to check if parentheses in a string are balanced using a stack.

Here is the code.

def is_balanced(expression):
    stack = Stack()
    opening_brackets = "([{"
    closing_brackets = ")]}"
    for char in expression:
        if char in opening_brackets:
            stack.push(char)
        elif char in closing_brackets:
            if stack.is_empty():
                return False
            top = stack.pop()
            if opening_brackets.index(top) != closing_brackets.index(char):
                return False
    return stack.is_empty()

# Example usage:
expression = "{[()]}"
print(is_balanced(expression))  # Output: True
 

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...