Reputation: 31
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:
cell.h that contains in the private section element and pointers to next cell, constructor-destructor and getters-setters.
stack.h that contains virtual pure methods (createStack()-emptyStack()-top().. )
stackp.h derived class of stack.h that redefine every method in stack.h and contains printPositiveStack().
template <class T>
void stackp<T>::printPositiveStack(){
stackp<T> auxp;
while(!this->emptyStack()){
int temp = this->top();
if(temp <= 0){
this->pop();
} else {
auxp.push(temp);
this->pop();
}
}
while(!auxp.emptyStack()){
this->push(auxp.top());
auxp.pop();
}
}
How can I create a function that returns a new stack without changing the original stack? Thanks!
Upvotes: 1
Views: 182
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
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:
Upvotes: 1