Created
November 26, 2018 07:19
-
-
Save hsinewu/8c1e50a07564e1de06bfce97065a74dd to your computer and use it in GitHub Desktop.
Simple stack implementation in c++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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