VS2019のC#で遊んでました。独習C#第3版P243課題3。スタックのサンプル。
using System;
namespace Chapter01All
{
class SimpleStack
{
char[] q; // スタックのデータを保持する配列
int poploc; // push操作やpop操作用の添え字
public SimpleStack(int size)
{
q = new char[size + 1]; // キュー用にメモリを確保する
poploc = 0;
}
// 1文字分だけスタックに追加する
public void Push(char ch)
{
if (poploc == q.Length - 1)
{
Console.WriteLine(" -- Stack is full.");
return;
}
q[poploc++] = ch;
}
// スタックから1文字分だけ取り出す
public char Pop()
{
if (poploc <= 0)
{
Console.WriteLine(" -- Stack is empty.");
return (char)0;
}
char w = q[--poploc];
q[poploc] = '.';
return w;
}
//スタックの表示
public void ShowStack()
{
for (int i = 0; i < q.Length; i++)
Console.Write(q[i]);
Console.WriteLine();
}
//スタックを'.'で埋める
public void FillStack()
{
for (int i = 0; i < q.Length; i++){
q[i] = '.';
}
}
}
// Stackクラスを使う
class StackDemo
{
static void Main()
{
int bigSSize = 20; int smallSSize = 4;
SimpleStack bigS = new SimpleStack(bigSSize);
SimpleStack smallS = new SimpleStack(smallSSize);
bigS.FillStack();
smallS.FillStack();
char ch;
int i;
Console.WriteLine("Using bigStack to store the alphabet.");
// bigSにいくつかの文字を追加する
bigS.Push('A'); bigS.ShowStack();
bigS.Push('B'); bigS.ShowStack();
bigS.Push('C'); bigS.ShowStack();
Console.WriteLine(bigS.Pop());bigS.ShowStack();
bigS.Push('1'); bigS.ShowStack();
Console.WriteLine("\n");
// bigSから取り出して表示する
Console.Write("Contents of bigS: ");
for (i = 0; i < bigSSize; i++)
{
ch = bigS.Pop();
if (ch == (char)0) break;
Console.Write(ch);
}
Console.WriteLine("\n");
Console.WriteLine("Using smallS to generate errors.");
// smallSを使ってエラーを起こさせる
for (i = 0; i < 5; i++)
{
Console.Write("Attempting to store " + (char)('Z' - i));
smallS.Push((char)('Z' - i));
Console.WriteLine();
}
Console.WriteLine();
// さらにsmallSでエラーを起こさせる
Console.Write("Contents of smallS: ");
for (i = 0; i < 5; i++)
{
ch = smallS.Pop();
if (ch != (char)0) Console.Write(ch);
}
Console.ReadKey();
}
}
}
Queueでは書き込むポイントと呼び出すポイントが必要でした。スタックの場合は、書き込むポイントを指すものだけあれば、Popするときは書き込むポイントの一個手前ですから、二つのポイントを覚えている必要はないようです。