c++ 实现栈类设计

初学者。。。自己学习的例子

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <stdlib.h>
using namespace std;

class CStuScore
{
public:
	CStuScore()//默认构造函数
	{
	}
	CStuScore(CStuScore &one)//默认拷贝构造函数
	{
		strcpy(strName, one.strName);
		strcpy(strStuNo, one.strStuNo);
		fScore[0] = one.fScore[0];
		fScore[1] = one.fScore[1];
		fScore[2] = one.fScore[2];
	}
	void SetData(char *strname, char *strno, float s1, float s2, float s3)
	{
		strcpy(strName, strname);
		strcpy(strStuNo, strno);
		fScore[0] = s1;
		fScore[1] = s2;
		fScore[3] = s3;
	}
	void OutPut(void)
	{
		cout<<"姓名:"<<strName<<endl;
		cout<<"学号:"<<strStuNo<<endl;
		cout<<"成绩:"<<fScore[0]<<","<<fScore[1]<<","<<fScore[2]<<endl;
	}
	void Input(void)
	{
		cout<<"姓名:";  cin>>strName;
		cout<<"学号:";  cin>>strStuNo;
		cout<<"成绩:";  cin>>fScore[0]>>fScore[1]>>fScore[2];
	}
private:
	char strName[12];
	char strStuNo[9];
	float fScore[3];
};
class Cstack
{
public:
	Cstack(int n_size)
	{
		m_size=n_size;
		buffer=new CStuScore[m_size];
		if(buffer!=NULL)
			sp=buffer;
		cout<<"栈空间已成功建立!"<<endl;

	}
	~Cstack()
	{
		if(buffer)
		{
			delete buffer;
			buffer=NULL;
			cout<<"栈空间释放!"<<endl;
		}
	}
	void push(CStuScore a)//入栈:先入栈*sp=a,在sp++,sp总是指向下一个
	{
		if(sp>buffer+m_size){
			cout<<"栈空间不足!"<<endl;
		}else
			*sp++=a;

	}
	CStuScore pop(void)//出栈:先sp--在弹出*sp
	{
		sp--;
		if(sp<buffer){
			cout<<"已越过栈底!"<<endl;
		}
			return *sp;
	}
private:
	CStuScore *sp;
	CStuScore *buffer;
	int m_size;
};

int main(void)
{
	Cstack one(5);
	CStuScore stu;

	stu.Input();
	one.push(stu);

	stu.SetData("DING","001",99,98,97);
	one.push(stu);

	stu.SetData("ZHANG","002",97,98,99);
	one.push(stu);

	cout<<"开始进行弹出操作!"<<endl;
	stu=one.pop();
	stu.OutPut();

	stu=one.pop();
	stu.OutPut();

	stu=one.pop();
	stu.OutPut();

	return 0;
}

<pre name="code" class="cpp">#include <iostream>
using namespace std;

typedef int T;

class Stack{
	T a[5];
	int cur;
public:
	Stack():cur(0){};
	void push(const T&d);
	T pop();
	const T& top()const;//栈顶数据
	bool empty(){return cur==0;};
	bool full(){return cur==5;};
	void clear(){cur=0;};
	int size(){return cur;};//栈数据个数
};

void Stack::push(const T&d){
	if(full()) return;
	a[cur++]=d;
}

T Stack::pop()
{
	if(empty()) return 1;
	return a[--cur];
}

const T& Stack::top()const
{
	return a[cur-1];
}

int main()
{
	Stack a;
	a.push(1);
	a.push(2);
	a.push(3);
	while(!a.empty()){
		cout<<a.pop()<<endl;
	}
};

 
 


  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值