jeudi 28 février 2019

Why Numbers are getting printed in the form like "12-256" , "13-256" rather than 12,13 etc.?

I'm solving one of the algorithms problem from university to implemet queue using stacks. I've got my logic right i guess but the numbers are getting printed in the form of 12-256, 13-256, 14-256 instead of 12,13,14.

Here's my C++ Code,

#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;
}

Here's my Output.

I'm basically a Python Guy so i'm not able to figure out what's wrong with this code.

I'm new to C++, so please guide me through this.

Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire