Skip to content

Instantly share code, notes, and snippets.

@sjgriffiths
Created January 7, 2018 20:13
Show Gist options
  • Save sjgriffiths/6e411eb272551640b1df9d9c236c8506 to your computer and use it in GitHub Desktop.
Save sjgriffiths/6e411eb272551640b1df9d9c236c8506 to your computer and use it in GitHub Desktop.
Queue and stack based on linked list (C++)
/**
Queue.h
Implements a class template of a queue
abstract data type.
@author Sam Griffiths
www.computist.xyz
*/
#pragma once
#include "DESLinkedList.h"
template <typename T>
class Queue : protected DESLinkedList<T>
{
public:
using DESLinkedList<T>::empty;
//Enqueues the given element
void enqueue(const T &elt)
{
this->add(elt, this->BACK);
}
//Dequeues the next element
void dequeue()
{
this->remove(this->FRONT);
}
//Returns the next element
T &peek()
{
return DESLinkedList<T>::peek(this->FRONT);
}
//Outputs the queue to the stream
friend std::ostream& operator<<(std::ostream &os, const Queue &q)
{
return os << static_cast<const DESLinkedList<T> &>(q);
}
};
template <typename T>
class Stack : protected DESLinkedList<T>
{
public:
using DESLinkedList<T>::empty;
//Pushes the given element
void push(const T &elt)
{
this->add(elt, this->FRONT);
}
//Pops the next element
void pop()
{
this->remove(this->FRONT);
}
//Returns the next element
T &peek()
{
return DESLinkedList<T>::peek(this->FRONT);
}
//Outputs the stack to the stream
friend std::ostream& operator<<(std::ostream &os, const Stack &q)
{
return os << static_cast<const DESLinkedList<T> &>(q);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment