Sobes.tech
Junior

Describe the main operations for data structures: stack and queue.

sobes.tech AI

Answer from AI

Stack

A stack is a data structure that operates on the LIFO (Last-In, First-Out) principle, where the last added element is the first to be removed.

Main operations:

  • Push: Add an element to the top of the stack.

    # Example of push operation in Python using a list
    stack = []
    stack.append(10) # Add element
    stack.append(20)
    # Now the stack: [10, 20] (20 on top)
    
  • Pop: Remove and return the element from the top of the stack. If the stack is empty, the operation may raise an error.

    # Example of pop operation
    element = stack.pop() # Remove element (20)
    # Now the stack: [10]
    # element == 20
    
  • Peek (or Top): Return the element from the top of the stack without removing it.

    # Example of peek operation
    if stack: # Check if the stack is not empty
        top_element = stack[-1]
        # top_element == 10
        # The stack remains unchanged: [10]
    
  • IsEmpty: Check if the stack is empty.

    # Example of is_empty operation
    is_empty = len(stack) == 0
    # is_empty == False in this case
    empty_stack = []
    is_empty_empty = len(empty_stack) == 0
    # is_empty_empty == True
    

Queue

A queue is a data structure that operates on the FIFO (First-In, First-Out) principle, where the first added element is the first to be removed.

Main operations:

  • Enqueue: Add an element to the end of the queue.

    # Example of enqueue operation in Python using collections.deque
    from collections import deque
    
    queue = deque()
    queue.append(10) # Add element to the end
    queue.append(20)
    # Now the queue: deque([10, 20]) (10 at the front, 20 at the end)
    
  • Dequeue: Remove and return the element from the front of the queue. If the queue is empty, the operation may raise an error.

    # Example of dequeue operation
    element = queue.popleft() # Remove element from the front (10)
    # Now the queue: deque([20])
    # element == 10
    
  • Front (or Peek): Return the element from the front of the queue without removing it.

    # Example of front operation
    if queue: # Check if the queue is not empty
        front_element = queue[0]
        # front_element == 20
        # The queue remains unchanged: deque([20])
    
  • IsEmpty: Check if the queue is empty.

    # Example of is_empty operation
    is_empty = len(queue) == 0
    # is_empty == False in this case
    empty_queue = deque()
    is_empty_empty = len(empty_queue) == 0
    # is_empty_empty == True