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.

/************************************************************
* Author: VNCODING
* History                  
* 2016/03/21        first create    VNCODING
*************************************************************/

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

lớp stack số nguyên
lớp stack số nguyên

1 Comment on Xây dựng lớp Stack cho số nguyên

Leave a Reply