I am implementing a stack and while it was a no-brainer to implement the basic operations push and pop, I am wondering how to implement somewhat efficient searching. The underlying structure is a linked list
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In its basic form, a stack would only allow slowish linear searches. I.e., if the stack has n elements, you would need to search through all n (1/2 n, on average) to find a match. If your stack is relatively small, this linear (one by one) search might not matter that much.
However, if you have a much larger set, you might be able to combine two data structures together to make searches more efficient: For example, you could have a hash table in addition to the stack: Each time you push something on the stack, you could also add it to the hash table. Conversely, when you remove it from the stack, you could remove it from the table. Hash tables allow relatively fast lookups, even with very large data sets– therefore, your searches could be quite fast.
One problem with my proposed solution is how to properly handle duplicate items: Stacks can hold dups, but hash tables typically don’t. Therefore, you might need to implement some simple reference counting in the hash table: Each time you pop, decrement the count in the hash table– when the count drops to zero, you can remove it from the hash.
Another similar possibility is to use a “multimap”– this is similar to a hash table, but would allow duplicates to be handled more easily.