views:

333

answers:

4

hi!

is there in C# some already defined generic container which can be used as Stack and as Queue at the same time? I just want to be able to append elements either to the end, or to the front of the queue

thanks

+2  A: 

What you want is a linked list - there's one in the BCL - that has AddFirst and AddLast methods

thecoop
+13  A: 

Check the LinkedList class.

LinkedList<int> list = new LinkedList<int>();

list.AddFirst(1);
list.AddLast(2);
list.AddFirst(0);
João Angelo
+7  A: 

Here's my implementation of an immutable deque:

http://blogs.msdn.com/ericlippert/archive/2008/02/12/immutability-in-c-part-eleven-a-working-double-ended-queue.aspx

Notice that this is an immutable double-ended-queue. Normally you probably think of a queue as something you mutate:

queue.Enqueue(10);

An immutable queue always stays the same; when you add a new element, it gives you back an entirely new queue, so you use it as:

queue = queue.Enqueue(10);

if you no longer care about the old value.

Eric Lippert
With all due respect, this doesn't appear to answer his question.
StriplingWarrior
The link has a class that defines what the OP was looking for. The example given in this answer doesn't really show that though.
s_hewitt
StriplingWarrior, I have no idea what you're talking about. The poster asks for an existing generic container which acts like a stack or a queue. Such a container is called a "deque", and I provided a link to source code for an implementation of such. Exactly which part of the question was not answered?
Eric Lippert
DeQueue is the right name here, LinkedList is 1 possible implementation of a DeQueue.
Henk Holterman
A: 

Good old List<T> will do it.

Add() to enqueue, Insert(0,T) to push, Remove(0) to pop/dequeue.

ebpower
Insert and Remove will both be O(n) operations. A linked list will be O(1)
thecoop
Cool - my first downvote. Thanks for pointing out the O(n). But to be picky, wouldn't it only be O(n) on inserts to the front of the List but not to the end (since it's Array-based)?
ebpower
That depends on which cost you are referring to. Are you talking about the *amortized* cost, or the *worst single case* cost? The amortized cost of inserting n items into the end of a double-when-full list is O(1). The worst-case cost of inserting one item int a double-when-full list of n items is O(n).
Eric Lippert