nic
nic

Reputation: 31

How to create a function that returns a new stack?

I'm doing my homework, I've created a stack by myself and want a function that create a new stack from a previous one that contains (e.g) only positive numbers.

I have done a void function that modifies the original stack and I can't keep it unmodified. The code is organised:

How can I create a function that returns a new stack without changing the original stack? Thanks!

Upvotes: 1

Views: 182

Answers (2)

CompuChip
CompuChip

Reputation: 9232

If you want to duplicate a stack using only its public interface, there is only one way to do it, which is unstack it (top-to-bottom), saving all the elements you see, then restacking onto both the new stack and the original one. Something like this:

std::vector<T> elements;
while(!originalStack.empty()) {
  elements.push_front(originalStack.pop());
}

for(T& element : elements) {
  // Note: be careful about using references here, depending on whether the stack
  // makes a copy of the elements (like vector does).
  originalStack.push(element);
  newStack.push(element);
}

If your function is a member of the stack class, e.g. a copy constructor, you may be able to (and probably should) do something more efficient by using the internals. How that would look depends on how you have implemented it, and you have not shown that code. But just as an example, suppose that your stack internally uses a vector to store the elements on the stack, your copy constructor could look a simple as this:

StackP<T>(const StackP<T>& other) 
  : elements(other.elements)
{
}

Upvotes: 1

Narase
Narase

Reputation: 490

It seems like you cant iterate over the raw data and are only able to see/pop the last inserted element. Given this assumption, I think your only chance is a algorithm with a farily bad performance:

  • Given you have Stack A
  • Create Stack B by top()'ing and pop()'ing the current Stack you which to copy and insert the elements in Stack B (it will be a reversal of your current Stack A)
  • Now do the same again, top()'ing and pop()'ing from Stack B, but now you copy the elements.
    • One for your current Stack A, so it will be the same as before
    • And one into your copy Stack C which you will then return

Upvotes: 1

Related Questions