c# stack queue combination

前端 未结 5 1742
南方客
南方客 2020-12-29 23:25

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,

5条回答
  •  北荒
    北荒 (楼主)
    2020-12-30 00:24

    Here's a class to help people implement this easily:

    public class StackQueue
    {
        private LinkedList linkedList = new LinkedList();
    
        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;
            }
        }
    }
    

提交回复
热议问题