Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a double sided stack class in .net?

Tags:

.net

I know about the System.Collections.Stack. I'm looking for a class that supports PushFront() & PushBack().

like image 806
Seth Reno Avatar asked Nov 10 '11 20:11

Seth Reno


People also ask

Does C# have stacks?

Stack represents a last-in, first out collection of object. It is used when you need a last-in, first-out access to items. When you add an item in the list, it is called pushing the item and when you remove it, it is called popping the item.

Why don't we use Stack classes?

The capacity of a Stack is the number of elements the Stack can hold. As elements are added to a Stack, the capacity is automatically increased as required through reallocation. We don't recommend that you use the Stack class for new development. Instead, we recommend that you use the generic System.

How do you declare a Stack in C#?

A Stack represents a last-in, first-out collection of objects. It is used when you need last-in, first-out access to items. It is both a generic and non-generic type of collection. The generic stack is defined in System.

What is Stack and queue in C#?

Queue and Stack are collection objects in the System. Collection namespace. The Queue class tracks objects on First-in & First-Out basis, while the Stack class tracks objects on First-in & Last-out basis. By using public methods of both Queue & Stacks classes, we can move objects to different locations.


2 Answers

It sounds like you want something normally called a deque. The closest I'm aware of in .NET is LinkedList<T>. I don't believe there's one built from a circular buffer (expanding as required), which is the way you'd probably want to build it from scratch.

Of course, you could implement it yourself - but I'd probably use LinkedList<T> unless I had a really good reason not to. Eric Lippert also has an immutable implementation you could look at (see his blog post covering it), but obviously you'd want to write a bunch of tests etc... and you may not want an immutable one.

like image 96
Jon Skeet Avatar answered Dec 29 '22 00:12

Jon Skeet


Why not just use/wrap LinkedList<T>? It has AddFirst and AddLast methods. You can wrap it to hide the AddBefore etc. methods.

The common term for this is deque (it means double ended queue). If for some reason wrapping a LinkedList<T> doesn't suffice (it should!), you could look at Eric Lippert's implementation of an immutable deque.

like image 31
jason Avatar answered Dec 29 '22 00:12

jason