Skip to content

Instantly share code, notes, and snippets.

@hsinewu
Created November 26, 2018 07:19
Show Gist options
  • Save hsinewu/8c1e50a07564e1de06bfce97065a74dd to your computer and use it in GitHub Desktop.
Save hsinewu/8c1e50a07564e1de06bfce97065a74dd to your computer and use it in GitHub Desktop.
Simple stack implementation in c++
#include <iostream>
// #include <stdexcept>
using namespace std;
template<typename T>
class Stack {
typedef struct Node {
T data;
struct Node* next;
} Node;
Node* top;
public:
T peek() {
if(top == nullptr)
throw runtime_error("Peek empty stack");
return top->data;
}
void push(T data) {
top = new Node{data, top};
}
void pop() {
if(!top)
throw runtime_error("Pop empty stack");
Node* n = top;
top = top->next;
delete n;
}
};
int main() {
Stack<int> s;
string cmd;
int arg;
while(cin >> cmd) {
if(cmd == "push") {
cin >> arg; s.push(arg);
} else if(cmd == "pop") {
s.pop();
} else if(cmd == "peek") {
cout << s.peek() << endl;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment