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

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;
        }
    }

相关文章:

  • 2021-11-12
  • 2021-12-28
  • 2021-06-22
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-04
猜你喜欢
  • 2022-01-22
  • 2021-10-23
  • 2022-01-08
  • 2021-07-31
  • 2021-11-08
  • 2022-12-23
相关资源
相似解决方案