栈(stack)的应用实例——将一个数组逆序输出

来源:互联网 发布:ubuntu搭建git服务器 编辑:程序博客网 时间:2024/06/11 02:01

#ifndef MAIN_SAVITCH_stack1_H
#define MAIN_SAVITCH_stack1_H
//#include <cstdlib>
#include <stdlib.h>
#include <float.h>
#include <math.h>
#include <stdio.h>
#include<limits.h>
#include<iostream>
using namespace std;
namespace main_savitch_7A
{
 template<class Item>
 class stack
 {
 public:
  typedef std::size_t size_type;
  typedef Item value_type;
  static const size_type CAPACITY = 30;
  stack(){ used=0; }
  void pop()
  {
   if (empty())
   {
    cout<<"栈已经为空"<<endl;
    return;
   }
   --used;
  }
  void push(const Item& entry)
  {
   assert(size()<CAPACITY);
   data[used]=entry;
   ++used;
  }
  bool empty() const { return (used==0); }
  size_type size() const { return used; }
  Item top() const
  {

   int index=used-1;
   if (index>=0)
   {
    return data[index];
   }
   else
   {
    return NAN;//--------------------------NAN
   }
   //return
  }
  //double x=NAN;
 private:
  Item data[CAPACITY];
  size_type used;
 };
}

#endif
//调用实施
int main()
{
int a[10]={0,1,2,3,4,5,6,7,8,9};
 
 main_savitch_7A::stack<int> asd;
 for (int i=0;i<10;++i)
 {
  asd.push(a[i]);
 }
 for (int i=asd.size();i>=0;--i)
 {
  cout<<asd.top()<<endl;
  asd.pop();
 }
 return 0;
}


0 0
原创粉丝点击