队列是先进先出,栈是先进后出,使用两个栈来模拟队列:
入队就是入第一个栈,出队是把第一个栈的元素全部出栈到第二个栈里,然后第二个栈出栈,再把剩下的倒回第一个栈。
<!--
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

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/12639172/viewspace-466047/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/12639172/viewspace-466047/
最后
以上就是活力篮球最近收集整理的关于用栈实现队列,实现Enqueue和Dequeue方法的全部内容,更多相关用栈实现队列内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复