.
Stack 跟 Queue 也都是最基本的資料結構之一
基本原則就是 Stack 為先進後出,類似電梯的進出模式
Queue 為先進先出,像是以前的收費站,也可以用水管來形容
這兩種資料結構都可以用來儲存所需要的資訊
但會依照用途的不同而採用不同的資料結構
向是經典的老鼠走迷宮就是用到 Stack來實作
主要為模擬遇到牆壁時會倒退的情況,因此用會用到先進後出的特性來返回原路徑
Queue則廣泛用於網路封包的傳遞,由於Server端可能要同時處理多個Client端
的封包,因此就會用Queue來儲存,將先進來的資料先做處理
如此一來也不會因為傳輸延遲而導致封包的接收順序亂掉
也可以更容易的還原完整的封包
以下為這次的範例程式,主要為動態模擬 Stack 跟 Queue 資料在進入與拋出的狀態
可以調整資料進出的速度,可以更明顯的觀察到兩者的差別
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- using System.Collections;
- using System.Threading;
-
- namespace Stack_Queue
- {
- public partial class Form1 : Form
- {
- // Creates and initializes a new Stack.
- Stack stack = new Stack();
- // Creates and initializes a new Queue.
- Queue queue = new Queue();
- Random rnd = new Random(Guid.NewGuid().GetHashCode());
- private delegate void UpdateUI(string str, Control ctl);
- private delegate void UpdateUI2(Queue Q, Control ctl);
- Thread _queue_stack_in, _queue_stack_out;
-
-
- public Form1()
- {
- InitializeComponent();
- }
-
- private void Form1_Load(object sender, EventArgs e)
- {
- _queue_stack_in = new Thread(Queue_Stack_In);
- _queue_stack_out = new Thread(Queue_Stack_Out);
-
- _queue_stack_in.Start();
- _queue_stack_out.Start();
-
- }
-
- private void Queue_Stack_In()
- {
- while(true)
- {
- int ramd_int = rnd.Next(10);
- stack.Push(ramd_int);
- updateText(ramd_int.ToString(), textBox1);
- updateText2(queue, textBox2);
-
- queue.Enqueue(ramd_int);
- updateText(ramd_int.ToString(),textBox6);
- updateText2(queue,textBox4);
- Thread.Sleep(Int32.Parse(numericUpDown1.Value.ToString()));
- }
- }
-
- private void Queue_Stack_Out()
- {
- while (true)
- {
- if (queue.Count > 0)
- {
- updateText(queue.Dequeue().ToString(), textBox5);
- }
- else
- {
- updateText("Empty", textBox5);
- }
-
- if(stack.Count > 0)
- {
- updateText(stack.Pop().ToString(), textBox3);
- }
- else
- {
- updateText("Empty", textBox3);
- }
- Thread.Sleep(Int32.Parse(numericUpDown2.Value.ToString()));
- }
- }
-
- private void updateText(string str, Control ctl)
- {
- if (this.InvokeRequired)
- {
- UpdateUI uu = new UpdateUI(updateText);
- this.Invoke(uu, str, ctl);
- }
- else
- {
- ctl.Text = str;
- }
- }
-
- private void updateText2(Queue Q, Control ctl)
- {
- if (this.InvokeRequired)
- {
- UpdateUI2 uu = new UpdateUI2(updateText2);
- this.Invoke(uu, Q, ctl);
- }
- else
- {
- ctl.Text = "";
-
- foreach (Object obj in queue)
- {
- ctl.Text += obj+" | ";
- }
- }
- }
-
- private void Form1_FormClosing(object sender, FormClosingEventArgs e)
- {
- _queue_stack_in.Abort();
- _queue_stack_out.Abort();
- }
- }
- }
執行畫面