【C++】一个简单栈的实现

一个简单的栈的实现

stack.h //栈数据结构的类定义

#ifndef STACK_H_INCLUDED
#define STACK_H_INCLUDED
typedef unsigned long Item;

class Stack
{
private:
    enum{MAX=10};   //栈的大小
    Item items[MAX];    //保存栈的数据的数组
    int top;    //指向栈顶的索引
public:
    Stack();
    ~Stack();
    bool isEmpty()const;
    bool isFull()const;
    //push() 如果栈已满返回false,否则返回true
    bool push(const Item& item);
    //pop() r如果栈为空返回false,否则返回true
    bool pop(Item& item);
};


#endif // STACK_H_INCLUDED
stack.cpp //栈的具体实现

#include"stack.h"

Stack::Stack()
{
    top=0;
}

Stack::~Stack()
{

}

bool Stack::isEmpty()const
{
    return top==0;
}

bool Stack::Stack::isFull()const
{
    return top==MAX;
}

bool Stack::push(const Item& item)
{
    if(top<MAX)
        {
            items[top++]=item;
            return true;
        }
    else
        {
            return false;
        }
}

bool Stack::pop(Item& item)
{
    if(top>0)
    {
        item=items[--top];
        return true;
    }
    else
    {
        return false;
    }
}

main.cpp //验证栈是否可用

#include <iostream>
#include "stack.h"
using namespace std;


int main()
{
    Stack stack1;
    char ch;
    unsigned long po;
    cout<<"输入A添加数据"<<endl
        <<"输入P弹出数据,Q退出"<<endl;


    while(cin>>ch&&toupper(ch)!='Q')
    {
        while(cin.get()!='\n')<span style="white-space:pre">	</span>//删除输入行剩余数字
            continue;
        if(!isalpha(ch))
        {
            cout<<"请输入正确的字符"<<endl;
            continue;
        }
        switch(ch)
        {
        case 'A':
        case 'a':
            cout<<"输入一个整数添加到栈: ";
            cin>>po;
            if(stack1.isFull())
                cout<<"栈已满,会溢出!"<<endl;
            else
                stack1.push(po);
            break;
        case 'p':
        case 'P':
            if(stack1.isEmpty())
                cout<<"栈为空,请确保栈中已有数据!"<<endl;
            else
            {
                stack1.pop(po);
                cout<<"POP #"<<po<<" 弹出!"<<endl;
            }
        break;
        }
        cout<<"输入A添加数据"<<endl
            <<"输入P弹出数据,Q退出"<<endl;
    }
    cout<<"Bye!"<<endl;
    return 0;
}

结果如图:



转载于:https://www.cnblogs.com/corfox/p/5415028.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值