我是靠谱客的博主 活力篮球,这篇文章主要介绍用栈实现队列,实现Enqueue和Dequeue方法,现在分享给大家,希望可以做个参考。

队列是先进先出,栈是先进后出,使用两个栈来模拟队列:

入队就是入第一个栈,出队是把第一个栈的元素全部出栈到第二个栈里,然后第二个栈出栈,再把剩下的倒回第一个栈。

 

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--&gt  1 using  System;
 2 using  System.Collections;
 3
 4 namespace  Algorithm
 5 expandedblockstart.gif {
 6    class Program
 7expandedsubblockstart.gif    {
 8        static void Main(string[] args)
 9expandedsubblockstart.gif        {
10            Queueq = new Queue();
11            q.Enqueue(1);
12            q.Enqueue(2);
13            q.Enqueue(3);
14            q.Enqueue(4);
15            Console.WriteLine(q.Dequeue());
16        }

17    }

18    class Queue
19expandedsubblockstart.gif    {
20        private Stack s1=new Stack();
21        private Stack s2=new Stack();
22
23        public void Enqueue(object o) 
24expandedsubblockstart.gif        {
25            s1.Push(o);
26        }

27        public object Dequeue() 
28expandedsubblockstart.gif        {
29            while (s1.Count > 0
30expandedsubblockstart.gif            {
31                s2.Push(s1.Pop());
32            }

33            object o = s2.Pop();
34            while (s2.Count > 0
35expandedsubblockstart.gif            {
36                s1.Push(s2.Pop());
37            }

38            return o;
39        }

40    }

41}

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/12639172/viewspace-466047/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/12639172/viewspace-466047/

最后

以上就是活力篮球最近收集整理的关于用栈实现队列,实现Enqueue和Dequeue方法的全部内容,更多相关用栈实现队列内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(68)

评论列表共有 0 条评论

立即
投稿
返回
顶部