简体   繁体   中英

Container for a stack of unique elements

What I'm trying to do is to construct a stack which contains unique elements.

And if an element is pushed to which is already in stack the element is not pushed but the existing elemetn should be moved to the top of the stack, ie ABCD + B > ACDB

I would like to here from you which container will be the best choice to have this functionality.

I decided to user stack adapter over list, because

  1. list does provide constant time for element move
  2. list is one of the natively supported containers for the stack.

The drawback of my choice is that I have to manually check for the duplicate elements.

PS My compiler is not so recent so please don't suggest unordered_set.

Basically you have to chose between constant time moving + long search, or constant time search + long moving.

It's hard to say which would be more time-consuming, but consider this:

  • You will have to search for if the element exists every time you try to add an element
  • You will not have to move elements every time, since obviously at some times you will be adding elements that are "new" for the container.

I'd suggest you to store elements and their stack positions in different containers. Store elements in a way that provides fast search, store stack positions in a way that provides fast movement. Connect both with pointers (so you can know which element is on which position, and which position holds which element <-- messy phrase, I know it!), and you will perform stuff rather fast.

From your requirements, it seems to me that the structure you want could be derived from a Max Heap .

If instead of storing just the item, you store a pair (generation, item), with generation coming from a monotonically increasing counter, then the "root" of the heap is always the last seen element (and the other elements do not really matter, do they ?).

  • Pop: typical pop operation on the heap ( delete-max operation)
  • Push: modified operation, to account for uniqueness of "item" within the structure
    • look for "item", if found update its generation ( increase-key operation)
    • if not, insert it ( insert operation)

Given the number of elements (20), building the heap on a vector seems a natural choice.

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