-->

算法导论第10章基本数据结构10.1栈

2020-09-20 20:34发布

 

 

 

 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 == 014 //     return TRUE15 // else return FALSE16 17 // PUSH(S, x)18 // S.top = S.top + 119 // S[S.top] = x20 21 // POP(S)22 // if STACK-EMPTY23 //     error "under flow"24 // else S.top = S.top - 125 //     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 to30     // a local variable n, see the constructor commented below31     stack(const int64_t& n) : top(-1), length(n)32     {33         data = new Type[n]();34     }/*
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_ */
标签: