队列是先进先出,栈是先进后出,使用两个栈来模拟队列:
入队就是入第一个栈,出队是把第一个栈的元素全部出栈到第二个栈里,然后第二个栈出栈,再把剩下的倒回第一个栈。
<!--
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
--> 1 using System;
2 using System.Collections;
3
4 namespace 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}
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
--> 1 using System;
2 using System.Collections;
3
4 namespace 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博客 ” ,链接:http://blog.itpub.net/12639172/viewspace-466047/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/12639172/viewspace-466047/