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

I4OK11V$Z(`77{BC(NQF0%1

 

S[~7)ZLGEORQ~6[FJTDAM[4

 

`3X(PBV9~6{D{DRYU8N)$V9

 

 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 }

 

 

 

 

 

7a7fe13598878e4397cc28e0158bd09e7c55f54a5ede27e47eea6fe26a3869877e752e8b1904cf5f075527a22bda53b57f48157d1119f39f73137f82d808e044

posted @ 2015-02-11 15:23  孙永杰  阅读(256)  评论(0编辑  收藏  举报