2.10 顺序栈

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值