/* 语言:C++ 编译环境:Visual C*+6.0 */
/*
利用类表示一个堆栈(stack),并为此堆栈建立向堆栈压入数据的函数
push(),从堆中弹出数据的函数pop()及显示堆栈数据的函数showstack()等
*/
/*-----------------------Stack.h-----------------------*/
// 类声明头文件Stack.h
#include <iostream>
using namespace std;
const int SIZE = 10;
class Stack
{
int stck[SIZE]; // 数组,用于存放栈中数据
int tos; // 栈顶位置(数组下标)
public:
Stack();
void push(int ch); // 声明向堆栈压入数据函数
int pop(); // 声明从堆栈中弹出数据函数
void ShowStack(); // 声明显示堆栈数据函数
};
/*----------------------Stack.cpp----------------------*/
// 类实现文件 Stack.cpp
#include "Stack.h"
// 构造函数,初始化栈的实现
Stack::Stack()
{ tos = 0; }
// 向堆栈压入数据函数的实现
void Stack::push(int ch)
{
if(tos == SIZE)
{
cout<<"Stack is full";
return; // 由于函数为void类型,因此直接return
}
stck[tos] = ch;
tos++;
cout<<"You have pushed a data into the stack!\n";
}
// 从堆栈中弹出数据函数的实现
int Stack::pop()
{
if(tos == 0)
{
cout<<"Stack is empty";
return 0;
}
tos--;
return stck[tos];
}
// 显示堆栈数据的函数
void Stack::ShowStack()
{
if(tos == 0)
{
cout<<"The stack has no data!\n";
return; // 由于函数为void类型,因此直接return
}
for(int i=tos-1; i >= 0; --i)
cout<<stck[i]<<" ";
cout<<endl;
}
/*--------------------Stackmain.cpp-------------------*/
// 类的使用文件 Stackmain.cpp
#include "Stack.h"
int main()
{
cout<<endl;
Stack ss; // 堆栈的对象
int x; // 输入数据
char ch; // 功能变量
cout<<" <I> ------ Push data to stack"<<endl;
cout<<" <O> ------ Pop data from stack"<<endl;
cout<<" <S> ------ Show the content of stack"<<endl;
cout<<" <Q> ------ Quit..."<<endl;
// switch语句实现功能循环选择
while(1)
{ // 功能选择
cout<<"\nPlease select an item: ";
cin>>ch;
ch = toupper(ch);
switch(ch)
{
case 'I':
cout<<"Enter the value that "<<"you want
to push: ";
cin>>x;
ss.push(x);
break;
case 'O':
x = ss.pop();
cout<<"Pop "<<x<<" from stack."<<endl;
break;
case 'S':
ss.ShowStack();
break;
case 'Q':
return 0;
default:
cout<<"You have inputted a wrong item!
Please try again!"<<endl;
continue;
}
}
}
C++ 学习之路(9):(附C++程序的多文件组成)堆栈示例
最新推荐文章于 2022-11-16 22:21:59 发布