[ACCEPTED]-c# stack queue combination-containers
Accepted answer
Check the LinkedList class.
LinkedList<int> list = new LinkedList<int>();
list.AddFirst(1);
list.AddLast(2);
list.AddFirst(0);
0
Here's my implementation of an immutable deque:
Notice that 7 this is an immutable double-ended-queue. Normally 6 you probably think of a queue as something 5 you mutate:
queue.Enqueue(10);
An immutable queue always stays 4 the same; when you add a new element, it 3 gives you back an entirely new queue, so 2 you use it as:
queue = queue.Enqueue(10);
if you no longer care about 1 the old value.
What you want is a linked list - there's one in the 1 BCL - that has AddFirst and AddLast methods
Here's a class to help people implement 1 this easily:
public class StackQueue<T>
{
private LinkedList<T> linkedList = new LinkedList<T>();
public void Push(T obj)
{
this.linkedList.AddFirst(obj);
}
public void Enqueue(T obj)
{
this.linkedList.AddFirst(obj);
}
public T Pop()
{
var obj = this.linkedList.First.Value;
this.linkedList.RemoveFirst();
return obj;
}
public T Dequeue()
{
var obj = this.linkedList.Last.Value;
this.linkedList.RemoveLast();
return obj;
}
public T PeekStack()
{
return this.linkedList.First.Value;
}
public T PeekQueue()
{
return this.linkedList.Last.Value;
}
public int Count
{
get
{
return this.linkedList.Count;
}
}
}
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.