Reputation: 419
I'd like to know whether there is a way of checking if an element exists or not in the stack. Assume that the stack interface has push, pop, isEmpty, getTop, member functions.
I know we can do it, if we get the top, compare it with that element and pop it, till it gets empty. But this method would be costy as we'd have to create another stacks to store the pop-ed elements and restore it again.
Upvotes: 0
Views: 2439
Reputation: 2275
Here's some pseudo-code for a method that checks for whether or not an element is in the stack:
template<class T>
bool find (stack<T> source, T value)
{
while (!source.isEmpty() && source.top() != value)
source.pop();
if (!source.isEmpty())
return true;
return false;
}
It's critical that the source stack is passed by value, so that it isn't modified. Also, realize that this solution probably isn't as efficient as using a different container than stack and simply calling a method which checks for a value.
Upvotes: 2