Remove Duplicates from stack (?)

Well first off, stack is not for that ! I mean what is the point of having list / collection / etc vs stack as different data structures ? But if still if you want to do so you can  do it this way.


Stack stack = new Stack();
stack = new Stack(stack.ToList().Distinct().Reverse());

I’d still insist to go this way :

List list = new List();

Stack stack = new Stack(list.Distinct().Reverse());

If you are wondering why did I use Reverse, stack is LIFO approach so if the order in which you added the items to “list” does not matter Or, you already are managing that order while adding items to the list Or, if you’re a performance geek … feel free to get rid of it. But as a rule of thumb I’d like to mention that : avoiding popping items off the stack should already improve performance with the run time having to deal with lesser items after every pop ! 😛

Leave a Comment

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s