2个堆栈实现自定义队列的入队出队方法 - 栈容量默认自动扩充

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyQueue
{
    public class MyQueue<T>
    {
        private bool _isStoredInLeft = true;
        private Stack<T> _left = new Stack<T>();
        private Stack<T> _right = new Stack<T>();
        public bool IsEmpty
        {
            get
            {
                if (_isStoredInLeft)
                {
                    return this._left.Count == 0;
                }
                else
                {
                    return this._right.Count == 0;
                }
            }
        }

        public MyQueue() { }

        public void Enqueue(T item)
        {
            Console.WriteLine("##Enqueue start!");
            if (this.IsEmpty || this._isStoredInLeft)
            {
                Console.WriteLine(" **Enqueue - left stack push:" + item.ToString());
                this._left.Push(item);
            }
            else
            {
                while (this._right.Count != 0)
                {
                    Console.WriteLine("    Enqueue - left stack push:" + this._right.Peek().ToString());
                    this._left.Push(this._right.Pop());
                }
                Console.WriteLine(" **Enqueue - left stack push:" + item.ToString());
                this._left.Push(item);
                this._isStoredInLeft = true;
            }
        }

        public T Dequeue()
        {
            Console.WriteLine("##Dequeue start!");
            if (this.IsEmpty)
            {
                throw new System.InvalidOperationException("Queue empty");
            }

            if (this._isStoredInLeft)
            {
                while (this._left.Count != 0)
                {
                    Console.WriteLine("    Dequeue - right stack push:" + this._left.Peek().ToString());
                    this._right.Push(this._left.Pop());
                }
                this._isStoredInLeft = false;
            }

            Console.WriteLine(" **Dequeue - right stack pop:" + this._right.Peek().ToString());
            return this._right.Pop();
        }
    }

    class Test
    {
        static void Main(string[] args)
        {
            MyQueue<int> q = new MyQueue<int>();
            for (int i = 0; i < 5; i++)
            {
                q.Enqueue(i);
            }
            for (int i = 0; i < 3; i++)
            {
                q.Dequeue();
            }
            for (int i = 5; i < 10; i++)
            {
                q.Enqueue(i);
            }
            while (!q.IsEmpty)
            {
                q.Dequeue();
            }
            q.Dequeue();
        }
    }
}


 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值