?? p2-108.cpp
字號:
#include<iostream.h>
#define MAX 5
//定義stack類接口
class stack{
int num[MAX];
int top;
public:
stack(char *name); //構造函數原型
~stack(void); //析構函數原型
void push(int n);
int pop(void);
};
//main()函數測試stack類
main(void)
{
int i,n;
//聲明對象
stack a("a"),b("b");
//以下利用循環和push()成員函數將2,4,6,8,10依次入a棧
for (i=1; i<=MAX; i++)
a.push(2*i);
//以下利用循環和pop()成員函數依次彈出a棧中的數據,并顯示
cout<<"a: ";
for (i=1; i<=MAX; i++)
cout<<a.pop()<<" ";
cout<<endl;
//從鍵盤上為b棧輸入數據,并顯示
for(i=1;i<=MAX;i++) {
cout<<i<<" b:";
cin>>n;
b.push(n);
}
cout<<"b: ";
for(i=1;i<=MAX;i++)
cout<<b.pop()<<" ";
cout<<endl;
return 0;
}
//-------------------------
// stack成員函數的定義
//-------------------------
//定義構造函數
stack::stack(char *name)
{
top=0;
cout << "Stack "<<name<<" initialized." << endl;
}
//定義析構函數
stack::~stack(void)
{
cout << "stack destroyed." << endl; //顯示信息
}
//入棧成員函數
void stack::push(int n)
{
if (top==MAX){
cout<<"Stack is full !"<<endl;
return;
};
num[top]=n;
top++;
}
//出棧成員函數
int stack::pop(void)
{
top--;
if (top<0){
cout<<"Stack is underflow !"<<endl;
return 0;
};
return num[top];
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -