Basic Data Structures

My Take on UCSD's Basic Data Structures course (CSE 12)


Project maintained by nate-browne Hosted on GitHub Pages — Theme by mattgraham

Stacks and Queues

Chapter 3 of Data Structures and Algorithm Analysis in C++

stack

The Motivation

Stacks and Queues are ADTs that represent some of the most normally occurring phenomena we see in day to day life.

Examples include:

Stacks

Firstly, we’ll talk about stacks.

Use Cases

Let’s give some practical coding examples for stacks!

Balancing Symbols

Q: Given a string, return true if the string has balanced symbols and false otherwise.

Examples:

”([{}])” –> true

“(hello there)” –> true

”{[}]” –> false

“General Kenobi” –> true

How would you approach this question? Discuss

Solution:

Create a stack. Read characters in. If you see a ‘(‘, ‘[’, or a ‘{‘, push it onto the stack. When you see one of the closing ones, pop off of the stack and check if you have a matching pair. Once you’re done reading the string, check if your stack is empty and return true if so. This runs in $O(n)$ time where n is the length of the string.

Infix to Postfix

Q: How do you turn something like 1 + 2 * 3 - (4 + 5) into the equivalent postfix?

Examples:

1 + 2 * 3 - (4 + 5) –> 1 2 3 * + 4 5 + -

Solution:

I’ll let you think about this one :)

Queues

Next, queues. Queues are known as First in, First out structures (FIFOs), and have many applications from normal waiting to process scheduling by the operating system.

C++ Feature: Introduction to Templates and Iterators

Pros:

Cons:

How do we use them?

Example Class: A Stack Outline Using Templates

#ifndef STACK_HPP
#define STACK_HPP

#include <iostream>
#include <vector>

template <class T>
class stack {
 private:
  std::vector<T> *vec; // The stack itself
 public:

  stack(void) {
    this->vec = new std::vector<T>();
  }

  ~stack(void) {
    delete this->vec;
  }

  bool empty(void); // Check if empty
  size_t size(void) const; // Get size of stack
  T & top(void) const; // Get element at top of stack
  void pop(void); // Remove element from top of stack
  void push(T &); // Insert element at top of stack
}


template <class T>
bool stack<T>::empty(void) {
  return this->vec->size();
}

.
.
.

#endif

Some notes:

  1. These template classes must go in header files! If you want to put the implementation code in a .cpp file, you’ll need an #include <filename>.cpp right above the #endif.
  2. Everything defined outside of the class must have a template <class classname> above it.
  3. You would initialize a stack by doing stack<int> s; to invoke the constructor.

Now, for iterators

Idea

Implementation

It’s a bit complex, so I’ll differ this to your own research.

That’s all folks! Next time, Linked Lists

back