Yêu cầu: xây dựng lớp Stack mô tả hoạt động của ngăn xếp cho số nguyên.
Code:
/************************************************************/
#include <iostream>
#include <iomanip>
#include <string.h>
using namespace std;
#define MAX_SIZE 100
class CStack
{
private:
int stack[MAX_SIZE]; // the maximum size
int size; //the actual size
public:
CStack(){size = 0;}
~CStack(){}
void push(int x);
int pop();
void show();
};
/************************************
*Function: push data into stack
*Return : void
************************************/
void CStack::push(int x)
{
if(size >= MAX_SIZE)
{
cout <<"Stack is overflow\n";
}
else
stack[size++] = x;
}
/************************************
*Function: pop data out of stack
*Return : element at top of stack
************************************/
int CStack::pop()
{
if(size == 0)
{
cout <<"Stack is empty\n";
}
else
{
return stack[--size];
}
}
/***************************************
*Function: show all of elements of stack
*Return : void
***************************************/
void CStack::show()
{
for (int i = 0; i < size; i++)
{
cout << "s[" << i << "] = " << stack[i] <<"\n";
}
}
void main()
{
CStack stack;
int x;
stack.push(4);
stack.push(-5);
stack.push(9);
stack.show();
x = stack.pop();
cout << "x = " << x << endl;
stack.show();
system("pause");
}
Kết quả:
1 2 3 4 5 6 |
s[0] = 4 s[1] = -5 s[2] = 9 x = 9 s[0] = 4 s[1] = -5 |
Leave a Reply