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.Push(1);
stack.Push(5);
stack.Push(1);
stack.Push(2);
stack.Push(3);
stack.Push(4);
stack.Push(1);
stack = new Stack(stack.ToList().Distinct().Reverse());

I’d still insist to go this way :


List list = new List();
list.add(1);
...
list.add(4);
list.add(1);

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 ! 😛

Advertisements

Published by

Aarsh Talati

Software Developer

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s