【win32程序控制台】练习题:堆栈数据增删过程的演示(来自c++primer plus p328~330)

时间:2022-08-19 08:05:18
/ * 程序的版权和版本声明部分 
* Copyright (c) 2012, 华南师范大学软件工程专业
* All rights reserved.
* 文件名称:堆栈数据增删过程的演示(来自c++primer plus p328~330)
* 作 者:Hookc
* 完成日期:2012 年4 月 10 日
* 版 本 号:1
* 对任务及求解方法的描述部分
* 输入描述:
* 问题描述:
* 程序输出:
* /

stack.h

#ifndef STACK_H_
#define STACK_H_

typedef unsigned long Item; //给unsigned long一个代名词Item

class Stack
{
private:
enum {MAX=10}; //利用枚举定义MAX,避免在声明中没有申请空间
Item items[MAX];
int top;
public:
Stack();
bool isempty()const;
bool isfull()const;
bool push(const Item&item); //push用于当堆栈满时返回false,其他返回true
bool pop(Item&item); //pop用于当堆栈空时返回false,其他返回true
};


#endif

stack.cpp

#include"stack.h"

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

bool Stack::isempty()const //判断堆栈是否空了
{
return top==0;
}

bool Stack::isfull()const //判断堆栈是否满了
{
return top==MAX;
}

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

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

usestack.cpp

/*堆栈过程的演示,增加一个数据项以及删除一个数据项的顺序演示*/

#include<iostream>
#include"stack.h"
#include<cctype>

int main()
{
using namespace std;
Stack st; //创建一个空的堆栈
char ch;
unsigned long po;
cout<<"Please enter A to add a purchase order,\n"<<"P to process a PO,or Q to quit.\n";
while(cin>>ch&&toupper(ch)!='Q') //toupper包含于头文件cctype中,如果ch是小写英文字母,则转换为大写,其他字符不变
{
while(cin.get()!='\n')
continue;
if(!isalpha(ch)) //包含于头文件cctype中,判断字符ch是否为英文字母
{
cout<<'\a'; //响铃提示输入错误
continue;
}
switch(ch)
{
case'A':
case'a':cout<<"Enter a PO number to add:";
cin>>po;
if(st.isfull())
cout<<"stack already full\n";
else
st.push(po);
break;
case'P':
case'p':if(st.isempty())
cout<<"stack already empty\n";
else
{
st.pop(po);
cout<<"PO #"<<po<<"popped\n";
}

break;
}

cout<<"Please enter A to add a purchase order,\n"
<<"P to process a PO,or Q to quit.\n";
}
cout<<"Bye~\n";
return 0;
}


学到了堆栈的基本操作流程

堆栈有一下几种可操作方法:

1、可创建空堆栈;

2、可将数据项添加到栈顶(压入);

3、可从栈顶删除数据项(弹出);

4、可查看堆栈是否填满;

5、可查看堆栈是否为空。