Algorithm 为什么数字会被打印成这样的形式;12-256“&引用;13-256“;而不是12、13等。?

Algorithm 为什么数字会被打印成这样的形式;12-256“&引用;13-256“;而不是12、13等。?,algorithm,c++11,data-structures,Algorithm,C++11,Data Structures,我正在解决一个从大学到使用堆栈实现队列的算法问题。 我想我的逻辑是正确的,但是数字是以12-256,13-256,14-256的形式打印出来的,而不是12,13,14 这是我的C++代码 #include <iostream> using namespace std; class Stack{ private: int arr[200]; int tos = -1; public: bool empty(){ return (tos

我正在解决一个从大学到使用堆栈实现队列的算法问题。 我想我的逻辑是正确的,但是数字是以12-25613-25614-256的形式打印出来的,而不是121314

这是我的C++代码

#include <iostream>

using namespace std;

class Stack{

private:
    int arr[200];
    int tos = -1;

public:

    bool empty(){
        return (tos == -1)?true:false;
    }

    void push(int element){
        arr[++tos] = element;
    }

    int pop(){
        return arr[tos--];
    }

    void show(){
        if(tos == -1){
            cout<<"stack empty";
        }else{
            for(int i=tos;i>0;i--)
                cout<<arr[i]<<"\t";
        }
    }

};


class Queue{

private:
    Stack s1,s2;


public:
    void enQueue(int x){

        //just using s1 to add new elements
        s1.push(x);
    }

    int deQueue(){

        if(s1.empty())
            throw 'e';

        else{
            int e;
            while(!s1.empty()){
                e = s1.pop();
                s2.push(e);
            }

            cout<<"\nelement to be removed:"<<s2.pop();

            if(s2.empty())
                throw 'f';

            else{
                int e;
                while(!s2.empty()){
                    e = s2.pop();
                    s1.push(e);
                }
            }
        }

    }
};

int main()
{
    try{
        Queue q1;
        q1.enQueue(12);
        q1.enQueue(13);
        q1.enQueue(14);
        q1.enQueue(15);

        cout<<q1.deQueue();
        cout<<q1.deQueue();
        cout<<q1.deQueue();
        cout<<q1.deQueue();
    }catch(char c){
        cout<<"\nstack empty!";
    }

    return 0;
}
#包括
使用名称空间std;
类堆栈{
私人:
int-arr[200];
int-tos=-1;
公众:
bool empty(){
返回(tos==-1)?真:假;
}
无效推送(int元素){
arr[++tos]=元素;
}
int-pop(){
返回arr[tos--];
}
无效显示(){
如果(tos==-1){

cout
出列
遇到以下问题

  • 它不会返回任何东西
  • s2
    在其顶部弹出后可以为空
  • 这里有一个更新版本应该可以使用

    int deQueue(){
    
       if(s1.empty())
          throw 'e';
    
       int e;
       while(!s1.empty()){
          e = s1.pop();
          s2.push(e);
       }
    
       int ret = s2.pop();
       cout<<"\nelement dequeued:"<< ret;
    
       // This is not correct.
       // It's OK for s2 to be empty after its top has been popped.
       // if(s2.empty())
       //    throw 'f';
    
       while(!s2.empty()){
          e = s2.pop();
          s1.push(e);
       }
    
       return ret;
    }
    

    如果您决定进行更改,则必须相应地更新
    enQueue
    deQueue

    您的
    deQueue
    不会返回任何内容。不要发布文本的屏幕截图。如果您在编译时启用了警告并注意到它们,则无需问此问题。您是否尝试过调试器?
    class Queue
    {
        private:
    
          Stack s;
    
       ...
    };