


1 /*
2 * IA_10.1_stack.h
3 *
4 * Created on: Feb 13, 2015
5 * Author: sunyj
6 */
7
8 #ifndef IA_10_1_STACK_H_
9 #define IA_10_1_STACK_H_
10
11 #include <cstdint>
12 // STACK-EMPTY(S)
13 // if S.top == 0
14 // return TRUE
15 // else return FALSE
16
17 // PUSH(S, x)
18 // S.top = S.top + 1
19 // S[S.top] = x
20
21 // POP(S)
22 // if STACK-EMPTY
23 // error "under flow"
24 // else S.top = S.top - 1
25 // return S[S.top + 1]
26
27 template <class Type> class stack {
28 public:
29 // length is a const reference, be careful, if n is not a const reference, length would be attached to
30 // a local variable n, see the constructor commented below
31 stack(const int64_t& n) : top(-1), length(n)
32 {
33 data = new Type[n]();
34 }
35 /*
36 stack(int64_t const n) : top(-1), length(n)
37 {
38 data = new int64_t[n]();
39 }
40 */
41 bool empty() { return -1 == top; }
42 int64_t push (Type x)
43 {
44 if (length == top + 1)
45 {
46 std::cout << "stack is full, push failed." << std::endl;
47 return -1 ;
48 }
49 data[++top] = x;
50 return 0 ;
51 }
52 int64_t pop(Type& x)
53 {
54 if(empty())
55 {
56 std::cout << "stack is empty, pop failed." << std::endl;
57 return -1;
58 }
59 x = data[top--];
60 return 0;
61 }
62 void PrintStack()
63 {
64 if (empty())
65 {
66 return;
67 }
68 for (int64_t i = 0; i < top + 1; i++)
69 {
70 std::cout << data[i] << " ";
71 }
72 std::cout << std::endl;
73 }
74 private:
75 Type* data;
76 int64_t top; // point to the top element of the stack
77 const int64_t& length;
78 };
79
80
81 #endif /* IA_10_1_STACK_H_ */
1 /*
2 * IA_10.1_stack.cpp
3 *
4 * Created on: Feb 11, 2015
5 * Author: sunyj
6 */
7
8 #include <iostream>
9 #include <stdio.h>
10 #include "IA_10.1_stack.h"
11
12 int main()
13 {
14 stack<int64_t> st(3);
15 std::cout << st.empty() << std::endl;
16 int64_t e;
17 if (0 == st.pop(e))
18 {
19 std::cout << e << std::endl;
20 }
21
22 st.PrintStack();
23 st.push(1);
24 st.push(5);
25 st.push(3);
26 st.push(4);
27 st.PrintStack();
28
29
30 if (0 == st.pop(e))
31 {
32 std::cout << e << std::endl;
33 }
34
35 st.PrintStack();
36 return 0;
37 }



