关闭

队列和栈

标签: C++积累
115人阅读 评论(0) 收藏 举报

队列  :先进先出,元素将在队列的尾部插入(入队,或者Enqueue),并从队列的头部移除(出对,或者Dequeue)。

栈:后进先出,元素在顶部入栈(push),也从顶部出栈(pop)。

eg:

Queue

using System;

using  System.Collections;

...

Queue numbers = new Queue();

...

//填充队列

foreach (int number in new int[4]{4,5,6,7})

{

      numbers.Enqueue(number );

      Console.WriteLine(number  + " has joined the queue");

}

...

//遍历队列

foreach (int number in numbers)

{

      Console.WriteLine(number);

}

......

//清空队列

while (numbers.Count >0)

{

      int number = (int )numbers.Dequeue();

      Console.WriteLine(number  + " has left the queue");

}

代码输出如下


3  has left the queue

4 has left the queue

5 has left the queue

6 has left the queue

3

4

5

6

3  has left the queue

4 has left the queue

5 has left the queue

6 has left the queue


Stack //栈

using System;

using  System.Collections;

...

Stack numbers = new Stack();

...

//填充栈  -  入栈  

foreach (int number in new int[4]{4,5,6,7})

{

      numbers.Push(number );

      Console.WriteLine(number  + " has been pushed on the stack");

}

...

//遍历栈

foreach (int number in numbers)

{

      Console.WriteLine(number);

}

......

//清空栈 - 出栈

while (numbers.Count >0)

{

      int number = (int )numbers.Pop();

      Console.WriteLine(number  + " has been popped off the stack");

}


代码输出如下

3 has been pushed on the stack

4 has been pushed on the stack

5 has been pushed on the stack

6 has been pushed on the stack

6

5

4

3

6 has been popped off the stack

5 has been popped off the stack

4 has been popped off the stack

3 has been popped off the stack




0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:5104次
    • 积分:151
    • 等级:
    • 排名:千里之外
    • 原创:9篇
    • 转载:10篇
    • 译文:0篇
    • 评论:0条
    文章存档