用C++中的vector實現的棧
沒事的時候隨便寫的,
模擬一下棧,
練習用C++寫程序
1
#include<iostream>
2
#include<vector>
3
using namespace std;
4
class Stack
5
{
6
public:
7
inline bool empty();
8
bool full();
9
bool push( int elem);
10
int pop();
11
void getmem();
12
int size()
{return _stack.size();}
13
private:
14
vector<int> _stack;
15
};
16
inline bool Stack::empty()
17
{
18
return _stack.empty();
19
}
20
21
inline bool Stack::full()
22
{
23
return _stack.size()==_stack.max_size();
24
}
25
bool Stack:: push(int elem)
26
{
27
if(full())
28
return false;
29
_stack.push_back(elem);
30
return true;
31
}
32
33
int Stack:: pop( )
34
{
35
if(empty())
36
return false;
37
int elem=_stack.back();
38
_stack.pop_back();
39
return elem;
40
}
41
void Stack::getmem()
42
{
43
if(empty())
44
return ;
45
cout<<_stack[0];
46
for(int ix=1;ix!=_stack.size();++ix)
47
cout<<' '<<_stack[ix];
48
cout<<endl;
49
}
50
int main()
51

{
52
Stack s;
53
cout<<s.size()<<endl;
54
for(int i=0,j=1;i<1000;)
55
{
56
s.push(i+j);
57
int k=i;
58
i=j;
59
j=k+i;
60
}
61
cout<<s.size()<<endl;
62
s.getmem();
63
s.pop();
64
s.pop();
65
s.getmem();
66
67
return 0;
68
}

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

61

62

63

64

65

66

67

68

posted on 2010-03-28 19:03 田兵 閱讀(870) 評論(0) 編輯 收藏 引用 所屬分類: 算法筆記