cs101-notes
  • CS 101 Notes
  • Big O Notation
  • Big O Cheat Sheet
  • Sorting
    • Summary
    • Bubble Sort
    • Selection Sort
    • Insertion Sort
    • Merge Sort
    • Quick Sort
  • Abstract Data Types
    • Linked List
    • Stack
    • Queue
    • Hash Maps
    • Minimum Ordered Heap
Powered by GitBook
On this page

Was this helpful?

  1. Abstract Data Types

Queue

First in, first out.

const int MAX = 999999;

template <typename eType>
struct Queue {
  eType array[MAX];
  int front, back, n;
  
  Queue() {
    front = 0;
    back = MAX - 1;
    n = 0;
  }
  
  void enqueue(eType x) {
    if (isFull()) throw "Queue is full";
    back = (back + 1) % MAX;
    array[back] = x;
    n += 1;
  }
  
  eType dequeue() {
    if (isEmpty()) throw "Queue is empty";
    eType x = array[front];
    front = (front + 1) % MAX;
    n -= 1;
    return x;
  }
  
  eType peek() {
    if (isEmpty()) throw "Queue is empty";
    return array[front];
  }
  
  boolean isEmpty() { return n == 0; }
  boolean isFull() { return n == MAX; }
  int size() { return n; }
};
PreviousStackNextHash Maps

Last updated 5 years ago

Was this helpful?