/*用C++的类写的栈比C好在:
1.代码层面:1.除了Push,其他不用传参了
2.调用栈的属性不用先通过结构体找属性->找了
3.函数直接写在类里面要用直接调类
4.构造函数可以缺省参数,提供选择,
2.调用直接.找成员,不用考虑怎么传指针,当作变量使用即可
注意:(不足)
栈方法得写:1.栈是否为空
2.栈的大小
(因为size是私有的,外部无接口查看)
*/
#include<iostream>
#include<stdlib.h>
#include<assert.h>
using namespace std;
//stack
typedef int StackDataType;
class Stack
{
StackDataType* array=nullptr;
int capacity = 0;
int size = 0;
public:
Stack(int num_array = 0)
{
if (num_array)
{
StackDataType* ptr = (StackDataType*)malloc(sizeof(StackDataType) * num_array);
if (ptr == nullptr)
perror("malloc");
array = ptr;
}
}
~Stack()
{
free(array);
array = nullptr;
}
bool StackExpansion()
{
if (size == capacity)
{
int newcapacity = capacity == 0 ? 4 : capacity * 2;
StackDataType* newptr = (StackDataType*)realloc(array, sizeof(StackDataType) * newcapacity);
if (newptr)
{
array = newptr;
capacity = newcapacity;
}
else
{
perror("StackExpansion");
return false;
}
}
return true;
}
void StackPush(StackDataType x)
{
if (!StackExpansion())
{
perror("StackPush");
return;
}
array[size++] = x;
}
void StackPop()
{
assert(size);
size--;
}
StackDataType StackTop()
{
assert(size);
return array[size - 1];
}
//判断是否为空
bool StackIsEmpty()
{
return size == 0;
}
//返回栈数据个数
int StackSize()
{
return size;
}
};
int main()
{
Stack stack(4);
int array[10] = { 1,2,3,4,5,6,7,8,9,10 };
for (int& e : array)
{
stack.StackPush(e);
}
while (!stack.StackIsEmpty())
{
cout << stack.StackTop()<<" ";
stack.StackPop();
}
cout << endl;
return 0;
}