首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

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

2012-09-14 
2个堆栈实现自定义队列的入队出队方法 - 栈容量默认自动扩充using Systemusing System.Collections.Gener

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楼JackLoveShen昨天 22:48
写的挺可以的!

热点排行