Hi, I am

Ngô Tôn

I am a programmer.

Home / Programming / C/C++ / Xây dựng lớp stack cho số nguyên

Xây dựng lớp stack cho số nguyên

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ả:

About ngoton

Ngô Tôn is a programmer with passion for tailored software solutions. Comes with 7+ years of IT experience, to execute beautiful front-end experiences with secure and robust back-end solutions.

Check Also

Xây dựng một lớp Time mô tả thông tin về giờ, phút giây

Yêu cầu: Xây dựng một lớp Time mô tả thông tin về giờ, phút giây. …

Leave a Reply

avatar
  Subscribe  
Notify of