stack - reverse of a queue in c++ -


this question exam paper got stuck in below have attached question although wasnt able complete have done of it.

question:

using following class definitions of stack , queue classes write templated function reversequeue(?), takes pointer queue parameter , uses stack object (or pointer stack object) reverse given queue. function call reversequeue should reverse data of queue passed parameter. [hint: call appropriate methods given below in reversequeue(?) function. not have write implementation code stack , queue classes/methods given below. read each method , use them according need.]

template <class t> struct node {     node<t> *pnext;     t data; };  template <class t> class stack{     private:        node<t> * top;      public:        stack();        ~stack();        void push (t data); //pushes new node data type //t in stack        bool pop (t &data); //pops out top node //the stack        void printstack(); //prints elements of stack };  template <class t> class queue {     private:         node<t> * front;         node<t> * tail;     public:         queue ();         ~queue();         bool dequeue ( t & data); //removes first node //a queue         bool enqueue (t val); //appends new node in //queue }; 

my answer incomplete not proceed further below answer whatever have done

template <class t> void reversequeue(queue <t> *ptr){     stack <t> *stackptr= new stack<t>;     t temp;     while(ptr->front !=null){          temp=ptr->data;         ptr->dequee(ptr->data);         stackptr->push(temp);       }      // incomplete code }  

if can give answer great

suppose input queue looks like

 1    2    3    4  ^              ^ front           

if dequeue items it, 1, 2, 3, 4.

suppose push these items onto stack dequeue them.
this:

4  <- top 3 2 1  <- bottom 

if pop these, 4, 3, 2, 1.

now, if enqueue these in queue pop them stack, get

 4    3    2    1  ^              ^ front           

which reverse of original queue.

something should it:

template <class t> void reversequeue(queue <t> *q){     stack <t> s;     t temp;     // first build stack (lifo queue) (fifo) queue.     while (q->dequeue(temp))     {         s.push(temp);     }     // first item in queue @ bottom of stack.     // last item @ top.     // queue empty.      // if enqueue them again reversed.     while (s.pop(temp))     {         q->enqueue(temp);     } }  

Comments

Popular posts from this blog

c++ - QTextObjectInterface with Qml TextEdit (QQuickTextEdit) -

javascript - angular ng-required radio button not toggling required off in firefox 33, OK in chrome -

xcode - Swift Playground - Files are not readable -