现在的位置: 首页 > 综合 > 正文

OJ常用动态数据输入方法 C++简单的栈编写及使用

2015年06月12日 ⁄ 综合 ⁄ 共 746字 ⁄ 字号 评论关闭

本博客介绍一种我们做OJ题目或ACM题目的时候经常会碰到的一些需要动态输入数据的方法,然而通常这种OJ题目智能包含标准输入输出库头文件,很多函数都要我们自己编写。本博客提供了一种数据动态输入方法,代码如下:


#include<iostream>
using namespace std;
const int stack_max = 10;
class stack
{
    int top;
    public:
        //定义为共有的可以实现向量般数组操作
        int num[stack_max];
        int getTop()
        {
            return top;
        }
        void init(void)
        {
            top = 0;
        }
        //压栈  int 类型数据
        void push(int x)
        {
            if(top == stack_max)
            {
                cout<<"The stack is full!\n";
                return ;
            }
            num[top] = x;
            top++;
        }
        //出栈
        int pop(void)
        {
            top--;
            if(top<0)
            {
                cout<<"The stack is underflow!\n";
                return 0;
            }
            return num[top];
        }
        //查找元素下标
        int getIndexByElem(int data)
        {
            int i ;
            for(i = 0;i<top;i++)
            {
                if(num[i] == data)
                {
                    return i;
                    break;
                }    
            }
            if(i == (top-1))
                return -1;
        }
}; 
int main()
{
    stack a;
    a.init();
    int j = 1;
    for(int i = 0;i<8;i++)
    {
        a.push(j);
        j *= 2;
    }
    int k = a.getTop();
    for(int i = 0;i<k;i++)
    {
        cout<<a.num[i]<<' ';
    }
    cout<<endl;
    cout<<"4  "<<a.getIndexByElem(16)<<endl;
}



抱歉!评论已关闭.