A stack is a data structure that follows the Last-In-First-Out (LIFO) principle. It's essentially a linear collection of elements with three primary operations: push, pop and peek.
Stacks are used to manage data in a way that ensures that the most recently added element is the first one to be removed.
This operation adds an element to the top of the stack.
This operation removes and returns the top element of the stack.
It retrieves the top element without removing it from the stack.
Checks whether the stack is empty.
Stack
Stacks are crucial for managing function calls in programming languages. When a function is called, its execution context is pushed onto the stack, and it's popped off when the function returns.
Stacks are used to evaluate mathematical expressions, particularly converting infix expressions (e.g., 2 + 3) to postfix notation (e.g., 2 3 +) and then evaluating them efficiently.
Stacks can be employed to implement undo and redo functionality in software applications. Each action or state change is pushed onto the stack and popped when the user requests an undo.
Algorithms like depth-first search (DFS) use stacks to keep track of choices made during exploration and backtrack when necessary.
Stacks are used in parsing and interpreting programming languages. They help ensure that the syntax is correctly structured, especially for languages with nested constructs (e.g., parentheses, curly braces).
Stacks are used in memory management for tracking allocated memory blocks and managing function call frames.
Web browsers use stacks to keep track of visited web pages, enabling users to navigate backward and forward through
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return len(self.items) == 0
def push(self, item):
self.items.append(item)
def pop(self):
if not self.isEmpty():
return self.items.pop()
else:
raise IndexError("Pop from an empty stack")
def peek(self):
if not self.isEmpty():
return self.items[-1]
else:
raise IndexError("Peek from an empty stack")
def size(self):
return len(self.items)
Which of the following is not an operation performed on a stack?
Which data structure follows the Last-In-First-Out (LIFO) principle?