Skip to content

Instantly share code, notes, and snippets.

@odarbelaeze
Last active October 11, 2020 17:52
Show Gist options
  • Save odarbelaeze/5376649 to your computer and use it in GitHub Desktop.
Save odarbelaeze/5376649 to your computer and use it in GitHub Desktop.
A DEQeue implementation in C++.
#include <exception>
#include <functional>
#include <iostream>
#include <stdexcept>
#include <string>
template<typename T>
class DEQeue
{
public:
enum class Iterate { BackToFront, FrontToBack };
DEQeue()
{
first_ = NULL;
last_ = NULL;
}
void push_front(const T& item)
{
if (first_ == NULL)
{
first_ = new Node();
first_ -> item = item;
first_ -> prev = NULL;
first_ -> next = NULL;
last_ = first_;
}
else
{
Node* oldFirst = first_;
first_ = new Node();
first_ -> item = item;
first_ -> prev = NULL;
first_ -> next = oldFirst;
oldFirst -> prev = first_;
}
}
void push_back(const T& item)
{
if (last_ == NULL)
{
last_ = new Node();
last_ -> item = item;
last_ -> prev = NULL;
last_ -> next = NULL;
first_ = last_;
}
else
{
Node* oldLast = last_;
last_ = new Node();
last_ -> item = item;
last_ -> prev = oldLast;
last_ -> next = NULL;
oldLast -> next = last_;
}
}
T pop_front()
{
if (isEmpty()) throw std::out_of_range("OMFG! The DEQeue was empty.");
T item = first_ -> item;
first_ = first_ -> next;
if (first_ == NULL) last_ = NULL;
return item;
}
T pop_back()
{
if (isEmpty()) throw std::out_of_range("OMFG! The DEQeue was empty.");
T item = last_ -> item;
last_ = last_ -> prev;
if (last_ == NULL) first_ = NULL;
return item;
}
bool isEmpty()
{
return first_ == NULL;
}
void each(std::function<void(T)> function, Iterate it = Iterate::FrontToBack)
{
if (it == Iterate::FrontToBack)
{
Node* node = first_;
while (node != NULL)
{
function(node -> item);
node = node -> next;
}
}
else
{
Node* node = last_;
while (node != NULL)
{
function(node -> item);
node = node -> prev;
}
}
}
private:
struct Node
{
T item;
Node* prev;
Node* next;
};
Node* first_;
Node* last_;
};
int main(int argc, char const *argv[])
{
enum class Latice { sc, bcc, fcc, hcp };
DEQeue<Latice> deqi;
for (int i = 10000000; i > 0; i --)
deqi.push_back(Latice::sc);
deqi.each([](Latice lt){
switch (lt)
{
case Latice::sc:
std::cout << "sc";
break;
case Latice::fcc:
std::cout << "fcc";
break;
case Latice::bcc:
std::cout << "bcc";
break;
case Latice::hcp:
std::cout << "hcp";
break;
}
std::cout << std::endl;
});
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment