杭电2031

第一次用stack,挺好用的,先进后出的特性很实用

c++ stl栈stack的头文件为

#include <stack> 

c++ stl栈stack的成员函数介绍

操作 比较和分配堆栈

empty() 堆栈为空则返回真

pop() 移除栈顶元素

push() 在栈顶增加元素

size() 返回栈中元素数目

top() 返回栈顶元素

扫描二维码关注公众号,回复: 1039886 查看本文章
下面是杭电2031的代码!

#include<iostream>
#include<stack>
using namespace std;
int main()//利用栈的先进后出 的特性
{
    int n;
    int r;
    stack<char>s;
    while(cin>>n>>r)
    {
        bool flag=true;
        if(n<0)
        {
            flag=false;
            n=-n;
        }
        while(n>0)
        {
            int temp=n%r;
            n/=r;
            if(temp>9)
            {
                temp=temp-10+'A';
            }
            else
            {
                temp=temp+'0';
            }
            s.push(temp);//将temp存到栈s中
        }
        if(!flag)
        {
            s.push('-');
        }
        while(!s.empty())
        {
            cout<<s.top();//输出栈顶端的元素
            s.pop();//删除栈顶端的元素
        }
        cout<<endl;




    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/intmainhhh/article/details/80376648