-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathstack.h
60 lines (55 loc) · 1.1 KB
/
stack.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
//
// stack.h
// stack+queue
//
// Created by junl on 2019/7/18.
// Copyright © 2019 junl. All rights reserved.
//
#ifndef stack_hpp
#define stack_hpp
#include <stdio.h>
#include <iostream>
#include "illegalParameterValue.h"
template <typename Value>
class stack {
public:
void push(const Value &v){
Node *node = new Node(v);
if (top) {
node->next = top;
top = node;
}else{
top = node;
}
}
Value& pop(){
if (top == nullptr)
throw stackEmpty();
Value &v = top->val;
top = top->next;
return v;
}
Value& topElement(){
if (top == nullptr)
throw stackEmpty();
Value &v = top->val;
return v;
}
void print(){
Node *ct = top;
while (ct) {
std::cout << ct->val << ", ";
ct = ct->next;
}
std::cout << std::endl;
}
private:
class Node{
public:
Value val;
Node *next;
Node(const Value &v):val(v),next(nullptr){}
};
Node *top;
};
#endif /* stack_hpp */