简体   繁体   中英

Checking whether an element exists in the stack

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM