1️⃣0️⃣ 顺序栈
#include <iostream>
using namespace std;
class mystack{
private:
int* Stack;
int top;
int capacity;
public:
mystack(int stackcapacity=10);
~mystack();
bool IsEmpty() const;
int Top() const;
void Push(const int i);
void Pop();
};
mystack::mystack(int stackcapacity):capacity(stackcapacity){
Stack = new int[capacity];
top = 0;
}
mystack::~mystack(){
delete []Stack;
Stack = NULL;
}
bool mystack::IsEmpty()const{
return capacity==0;
}
int mystack::Top()const{
return Stack[top-1]; //这个减1不能漏,不然top就指的是还未入栈的那个位置了
}
void ChangeSize(int* p, int oldsize, int newsize){
int* temp = new int[newsize];
int number = min(oldsize, newsize);
copy(p,p+number,temp);
delete []p;
p = temp;
}
void mystack::Push(const int i){
Stack[top++] = i;
if(top == capacity)
ChangeSize(Stack,capacity,2*capacity);
}
void mystack::Pop(){
top--;
}
int main(){
mystack st(12);
st.Push(23);
cout << st.Top() << endl;
st.Push(32);
cout << st.Top() << endl;
st.Push(4);
cout << st.Top() << endl;
st.Push(16);
cout << st.Top() << endl;
st.Pop();
cout << st.Top() << endl;
return 0;
}