Skip to content

Instantly share code, notes, and snippets.

@NathanEpstein
Created February 6, 2015 16:26
Show Gist options
  • Save NathanEpstein/d237903c7fc7d14b345d to your computer and use it in GitHub Desktop.
Save NathanEpstein/d237903c7fc7d14b345d to your computer and use it in GitHub Desktop.
C++ implementation of queue and stack
#include <list>
#include <iostream>
using namespace std;
// Implement Q class
class Q{
public:
Q();
~Q();
void enqueue(int n);
int dequeue();
private:
list<int> queue;
};
Q::Q(){
list<int> queue;
}
Q::~Q(){}
void Q::enqueue(int n){
queue.push_back(n);
}
int Q::dequeue(){
int n = queue.front();
queue.pop_front();
return n;
}
//Implement Stack class
class Stack{
public:
Stack();
~Stack();
void push(int n);
int pop();
private:
list<int> stack;
};
Stack::Stack(){
list<int> stack;
}
Stack::~Stack(){}
void Stack::push(int n){
stack.push_back(n);
}
int Stack::pop(){
int n = stack.back();
stack.pop_back();
return n;
}
// Create examples
int main(){
Q q;
Stack s;
for(int i=0;i<5; i++){
q.enqueue(i);
s.push(i);
}
cout<<"Empty the queue:"<<'\n';
//empty the queue: 0,1,2,3,4
for(int i=0;i<5;i++){
cout<<q.dequeue()<<'\n';
}
cout<<"Empty the stack:"<<'\n';
// empty the stack: 4,3,2,1,0
for(int i=0;i<5;i++){
cout<<s.pop()<<'\n';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment