Doubt pop procedure stacks c ++

1

this code shows in reverse order the contents of the list linked from node n with the help of a stack. One question, if instead of showing the content of the list in reverse order, I want to show it in normal order, how should I handle the stack to show it that way?

This is the code that shows the data in reverse order, I want to know what I have to modify to show in normal order, from the first position to the last one. Help is appreciated.

template <class T>
  ostream& dll_t<T>::write_reverse2(dll_node_t<T>* n, ostream& os) const {   



    stack_v_t<dll_node_t<T>*> stack;

    while (n != NULL) {
        stack.push_back(n);
        n = n->get_next();
    }

    while(!stack.empty()){

        stack.top()->write(os);
        stack.pop();
    }

    return os;
}

template <class T>
ostream& dll_t<T>::write_reverse2(ostream& os) const {

    reverse2(head_, os);

    return os;
}

template <class T>
class stack_v_t{
private:
vector_t<T> v_;
int top_;
public:
stack_v_t(int max_sz);
~stack_v_t(void);
bool empty(void);
T top(void);
void pop(void);
void push(T dato);
};
    
asked by AER 25.07.2017 в 14:30
source

1 answer

2

The batteries are either FIFO type or LIFO type. That is, the order in which the elements are extracted is fixed in advance.

The one you indicate has all the appearance of being a LIFO type and that you will not be able to change it.

Even so, to show the data in direct order you can choose to ignore the stack:

template <class T>
ostream& dll_t<T>::write(dll_node_t<T>* n, ostream& os) const
{   
  while (n != NULL) {
    n->write(os);
    n = n->get_next();
  }

  return os;
}

If you want to do it with batteries, the solutions become simply absurd:

Use a FIFO stack

I do not know if this possibility is available. It would be absurd because instead of showing the data directly (as I proposed at the beginning), you would store these results in an intermediate stack that would not contribute anything.

Use two LIFO batteries

In this case the absurd thing is to have to resort to two batteries to obtain the same result that you get with the first answer:

template <class T>
ostream& dll_t<T>::write_reverse2(dll_node_t<T>* n, ostream& os) const
{   
    stack_v_t<dll_node_t<T>*> stack1, stack2;

    while (n != NULL) {
        stack1.push_back(n);
        n = n->get_next();
    }

    while(!stack1.empty()){
      stack2.push_back(stack1.top());
      stack1.pop();
    }

    while(!stack2.empty()){
      stack2.top()->write(os);
      stack2.pop();
    }

    return os;
}
    
answered by 25.07.2017 / 14:42
source