スタック (Stack) のデータ構造を利用する - C#
C#でスタックのデータ構造を利用したデータ格納のコードを紹介します。
概要
C#でスタックを利用する場合は、System.Collections 名前空間の Stack クラスを用います。
プログラム例
UI
下図のUIを作成します。テキストボックスとボタンを1つずつ配置します。
コード
下記のコードを記述します。
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace StackDemo
{
public partial class FormDemo1 : Form
{
public FormDemo1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Stack stack = new Stack();
stack.Push("ペンギン");
stack.Push("くじら");
stack.Push("しろくま");
stack.Push("アヒル");
stack.Push("ヤンバルクイナ");
string text;
for (int i = 0; i < 5; i++) {
text = (string)stack.Pop();
textBox_Output.Text += text + "\r\n";
}
}
}
}
解説
下記のコードでStackクラスのインスタンスを作成します。
Stack stack = new Stack();
下記のコードで作成したスタックオブジェクトに文字列のデータをプッシュして追加します。
stack.Push("ペンギン");
stack.Push("くじら");
stack.Push("しろくま");
stack.Push("アヒル");
stack.Push("ヤンバルクイナ");
スタックからデータをポップし、取得したデータをテキストボックスに表示します。
for (int i = 0; i < 5; i++) {
text = (string)stack.Pop();
textBox_Output.Text += text + "\r\n";
}
実行結果
プロジェクトを実行します。下図のウィンドウが表示されます。
[Button1]をクリックします。スタックから取り出されたデータがテキストボックスに表示されます。スタックにプッシュした順番の逆順(LIFO(Last In, First Out, 後入れ先出し)でテキストボックスに値が表示されます。
補足
スタックの内容すべてを出力するのであれば、whileループを利用した、下記のコードが良いです。
private void button1_Click(object sender, EventArgs e)
{
Stack stack = new Stack();
stack.Push("ペンギン");
stack.Push("くじら");
stack.Push("しろくま");
stack.Push("アヒル");
stack.Push("ヤンバルクイナ");
string text;
while (stack.Count > 0) {
text = (string)stack.Pop();
textBox_Output.Text += text + "\r\n";
}
}
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用