基本数据结构之Stack类(一)

//=====================Stack.h=================

#include<iostream>
using namespace std;
template<typename DataType> class Stack
{
 public:
  Stack(int size)
  {
   maxSize=size;
   top=-1;
   elements=new DataType[size];
  }
  ~Stack()
  {
   delete [] elements;
  }
  //入栈操作
  bool push(DataType data);
  //出栈
  DataType pop();
 private:
  DataType *elements;
  int top;//栈顶序号
  int maxSize;栈空间
};
template<typename DataType>bool Stack<DataType>::push(DataType data)
{
 if(top==maxSize)
  return false;
 elements[++top]=data;
 return true;
}
template<typename DataType> DataType Stack<DataType>::pop()
{
 if(top==-1)
 {
  exit(1);
 }
 return elements[top--];
}


//=======================Stack.cpp==================

#include<iostream>
#include"stack.h"
using namespace std;
/*
int main()
{
 Stack<int> s=Stack<int>(6);
 int temp=0;
 s.push(23);
 s.push(56);
 s.push(11);
 temp=s.pop();
 cout<<temp<<" ";
 s.push(4);
 temp=s.pop();
 cout<<temp<<" ";
 temp=s.pop();
 cout<<temp<<" ";
 s.push(86);
 s.push(98);
 temp=s.pop();
 cout<<temp<<" ";
 temp=s.pop();
 cout<<temp<<" ";
 temp=s.pop();
 cout<<temp<<" ";
 return 0;
}
*/
int main()
{
 int size;
 printf("请输入栈的大小:\n");
 scanf("%d",&size);
 Stack<int> ss=Stack<int>(size);
    int temp;
 printf("请输入栈元素:\n");
 for(int i=0;i<size;i++)
 {
  int a;
  scanf("%d",&a);
  ss.push(a);
 }
 for(i=0;i<size;i++)
 {
  temp=ss.pop();
  cout<<temp<<endl;
 }
 return 0;
}

//栈的特点是先进后出主要有两个操作入栈和出栈。都是在栈顶进行操作。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值