Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Stacks | Advanced Data Structures
Algorithms and Data Structures Overview
course content

Course Content

Algorithms and Data Structures Overview

Algorithms and Data Structures Overview

1. Introduction to ADS
2. List and Array
3. Advanced Data Structures
4. Graphs

Stacks

A stack data structure is a so-called LIFO (Last In, First Out) data structure. It means that the last item inserted in the stack will be the first item removed. And, of course, it is very important that we can access only the last element in a data structure exclusively when dealing with the stack.

Stack implementation

1234567891011121314151617181920212223242526272829
import numpy as np class Stack: def __init__(self): self.stack = np.array([]) # Initialize an empty NumPy array def push(self, item): self.stack = np.append(self.stack, item) # Append the item to the end of the array def pop(self): if not self.is_empty(): return_value = self.stack[-1] # Store the value to return self.stack = np.delete(self.stack, -1) # Remove the last item from the array return return_value # Return the removed item else: return None # Return None if the stack is empty # Example usage: stack = Stack() stack.push(1) stack.push(2) stack.push(3) print("Stack:", stack.stack) print("Pop:", stack.pop()) print("Stack after pop:", stack.stack)
copy

It is important to remember that a stack is an abstract data type. It means that it only defines behavior but not a concrete implementation. The stack abstract data type can be implemented either with the help of the array or linked list data structure.

Usually, in concrete implementations of the stack, two basic methods are used:

  • push() - inserts an item into a stack;
  • pop() - removes the last inserted item from a stack.

Basic operations time complexity

In a stack, which element is at the bottom?

Select the correct answer

Everything was clear?

Section 3. Chapter 1
We're sorry to hear that something went wrong. What happened?
some-alt