c# stack queue combination

2019-02-04 04:22发布

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

5条回答
成全新的幸福
2楼-- · 2019-02-04 05:06

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.

查看更多
Animai°情兽
3楼-- · 2019-02-04 05:09

Good old List<T> will do it.

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

查看更多
Viruses.
4楼-- · 2019-02-04 05:17

Check the LinkedList class.

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

list.AddFirst(1);
list.AddLast(2);
list.AddFirst(0);
查看更多
smile是对你的礼貌
5楼-- · 2019-02-04 05:18

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

查看更多
Melony?
6楼-- · 2019-02-04 05:25

Here's a class to help people implement 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;
        }
    }
}
查看更多
登录 后发表回答