Home > front end >  How do I copy values from one stack to another?
How do I copy values from one stack to another?

Time:03-25

I am stuck after popping the values from stack1 then trying to push those values back into stack1, to later push back into stack2 in order. I'm not sure if I need another loop to make it nested loops or if I should switch to for loops as they are counting loops.

void copyStack(stack<int>& stack1, stack<int>& stack2)
{
   int size = stack1.size();
   while(size > 0)
   {
 
      stack2.push(stack1.top());
      stack1.pop();
      stack1.push(stack2.top());
      --size;
      
   }
   

}

Example:

Stack1: 4 3 2 1

Stack2: (empty)

(after running the function...)

Stack1: (empty)

Stack2: 4 3 2 1

CodePudding user response:

If you pop the values from one stack and push them onto another, they'll be in the reverse of their original order. You need an intermediate stack if you want them in the original order. Pop all values from stack1 and push then to stackTemp, then do the same from stackTemp to stack2.

CodePudding user response:

I'm a bit confused, why don't you just use this:

void copyStack(stack<int>& stack1, stack<int>& stack2) {
    stack2 = stack1;
}

It's C ;)

Or, if you want to swap elements of these two stacks, instead of copying, you can use:

stack1.swap(stack2);

EDIT: if you want to do it by yourself and looking for an interesting solution, you can try these links: Clone a stack without extra space

Clone a stack without using extra space | Set 2

  • Related