两个由栈组成的队列和两个由队列组成的栈

今天看《算法导论》看到两个如题的两个习题,遂做之。没有做参数检查以及异常处理,线程安全等。

class DoubleStackQueue
    {
        private System.Collections.Stack stackA, stackB;

        public DoubleStackQueue()
        {
            stackA = new System.Collections.Stack();
            stackB = new System.Collections.Stack();
        }

        public void Enqueue(object obj)
        {
            stackA.Push(obj);
        }

        public object Dequeue()
        {
            while (stackA.Count != 0)
                stackB.Push(stackA.Pop());

            return stackB.Pop();
            }
    }
 
class DoubleQueueStack
    {
        private System.Collections.Queue queueA, queueB;

        public DoubleQueueStack()
        {
            queueA = new System.Collections.Queue();
            queueB = new System.Collections.Queue();
        }

        public void Push(object obj)
        {
            while (queueA.Count != 0)
                queueB.Enqueue(queueA.Dequeue());
            queueA.Enqueue(obj);
            while (queueB.Count != 0)
                queueA.Enqueue(queueB.Dequeue()); 
        }

        public object Pop()
        {
            return queueA.Dequeue();
        }
    }

 

改进的:DoubleQueueStack

class DoubleQueueStack
    {
        private System.Collections.Queue queueA, queueB;

        public DoubleQueueStack()
        {
            queueA = new System.Collections.Queue();
            queueB = new System.Collections.Queue();
        }

        public void Push(object obj)
        {
            if (queueA.Count == 0 && queueB.Count == 0)
                queueA.Enqueue(obj);
            else
            {
                if (queueA.Count == 0) queueB.Enqueue(obj);
                else queueA.Enqueue(obj);
            }
        }

        public object Pop()
        {
            if (queueA.Count == 0)
            {
                while (queueB.Count != 1)
                    queueA.Enqueue(queueB.Dequeue());
                return queueB.Dequeue();
            }
            else if (queueB.Count == 0)
            {
                while (queueA.Count != 1)
                    queueB.Enqueue(queueA.Dequeue());
                return queueA.Dequeue();
            }
            return null;
        }
    }

posted @ 2010-12-29 15:05  DiggingDeeply  阅读(388)  评论(0编辑  收藏  举报