0%

动态顺序栈(C++)

参考

源码

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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include<iostream>
using namespace std;

template<class T>
class Stack
{
public:
Stack():_pData(new T[1]), _capacity(1), _size(0)
{
cout << "creat stack successful" << endl;
}
~Stack()
{
delete [] _pData;
cout << "delete stack successful" << endl;
}
void Push(const T& t)
{
CheckCapacity();
_pData[_size++] = t;
cout << "push " << t << " successful" << endl;
}
T& Pop()
{
T& t = _pData[_size-1];
_size--;
// cout << "pop return " << t << endl;
return t;
}
size_t Size()const
{
return _size;
}
size_t Capacity()const
{
return _capacity;
}

private:
void CheckCapacity()
{
size_t size = Size();
size_t capacity = Capacity();
size_t newcapacity = 2 * capacity;
if (size >= capacity)
{
_capacity = newcapacity;
T* tmp = new T[newcapacity];
for (size_t i = 0; i<size; i++)
{
tmp[i] = _pData[i];
}
delete[] _pData;
_pData = tmp;
cout << "capacity add to " << newcapacity << endl;
}
}

private:
T* _pData;
size_t _capacity;
size_t _size;
};

int main(void)
{
Stack<char> s;
char strInput[100]="test\0";
int i = 0;
cout << "input:";
if(!cin.getline(strInput,100))
cout << "error, input too long" << endl;
while(strInput[i] != '\0')
{
s.Push(strInput[i]);
i++;
}
i = 0;
cout << "output:";
while(strInput[i] != '\0')
{
cout << s.Pop();
i++;
}
cout << endl;
system("pause");
return 0;
}

运行结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
creat stack successful
input:i love tzy
push i successful
capacity add to 2
push successful
capacity add to 4
push l successful
push o successful
capacity add to 8
push v successful
push e successful
push successful
push t successful
capacity add to 16
push z successful
push y successful
output:yzt evol i

  1. Sublime里运行程序不能输入数据,只能输出数据(卡在cin)
  2. 参考:动态顺序栈的简单实现 中,数组扩容未改变_capacity