ITPub博客

首页 > Linux操作系统 > Linux操作系统 > 用栈实现队列,实现Enqueue和Dequeue方法

用栈实现队列,实现Enqueue和Dequeue方法

原创 Linux操作系统 作者:iDotNetSpace 时间:2008-09-28 15:09:27 0 删除 编辑

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

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

 

<!--

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

--> 1using System;
 2using System.Collections;
 3
 4namespace Algorithm
 5{
 6    class Program
 7    {
 8        static void Main(string[] args)
 9        {
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
19    {
20        private Stack s1=new Stack();
21        private Stack s2=new Stack();
22
23        public void Enqueue(object o) 
24        {
25            s1.Push(o);
26        }

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

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

38            return o;
39        }

40    }

41}

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

上一篇: 反射
下一篇: 自动内存管理
请登录后发表评论 登录
全部评论

注册时间:2008-01-04

  • 博文量
    2376
  • 访问量
    5765918