暇つぶしにWindowsFormアプリで
自前でStackとQueueを作ってみました。
環境:
Visual Studio Professional 2015
C#.NET 4.6
未熟なので駄目出しコメントあれば
ドシドシください!!
追記:
コメントを頂き、ソースをそれぞれクラス化して更新しました。
恥ずかしながらstring.Joinメソッド知りませんでした……
string.Splitの逆って感じですね。
雛形までご用意いただきありがとうございました!
Stack
using System.Linq;
namespace StackQueue
{
class MyStack
{
#region Field
private int size { get; set; }
private string[] stack { get; set; }
private int idxStack { get; set; }
#endregion
public MyStack(int size)
{
this.size = size;
this.stack = new string[size];
this.stack.Select(x => "");
}
/// <summary>
/// Push
/// </summary>
/// <param name="num"></param>
public void Push(string num)
{
stack[idxStack] = num;
if (idxStack < size - 1)
{
idxStack++;
}
}
/// <summary>
/// Pop
/// </summary>
/// <returns></returns>
public string Pop()
{
if (this.isNeededDecrementByStack())
{
idxStack--;
}
string buf = stack[idxStack];
stack[idxStack] = "";
return buf;
}
/// <summary>
/// スタック出力
/// </summary>
public string ExportStack()
{
var stackFormat = new string[size];
this.stack.CopyTo(stackFormat, 0);
// Pop対象に[]を付ける
if (this.stack.Any(x => x != ""))
{
if (this.isNeededDecrementByStack())
{
stackFormat[idxStack - 1] = $"[{stackFormat[idxStack - 1]}]";
}
else
{
stackFormat[idxStack] = $"[{stackFormat[idxStack]}]";
}
}
return string.Join(", ", stackFormat);
}
/// <summary>
/// スタックがデクリメント必要かの確認
/// </summary>
/// <returns></returns>
private bool isNeededDecrementByStack()
{
if (0 < idxStack && idxStack < size - 1
|| idxStack == size - 1 && string.IsNullOrEmpty(this.stack[idxStack]))
{
return true;
}
else
{
return false;
}
}
}
}
Queue
using System.Linq;
namespace StackQueue
{
class MyQueue
{
#region Field
private int size { get; set; }
private string[] queue { get; set; }
private int idxEnQueue { get; set; }
private int idxDeQueue { get; set; }
#endregion
public MyQueue(int size)
{
this.size = size;
this.queue = new string[size];
this.queue.Select(x => "");
}
/// <summary>
/// EnQueue
/// </summary>
/// <param name="num"></param>
public void EnQueue(string num)
{
if (!string.IsNullOrEmpty(queue[idxEnQueue])) { return; }
queue[idxEnQueue] = num;
idxEnQueue = (idxEnQueue + 1) % size;
}
// <summary>
/// DeQueue
/// </summary>
/// <returns></returns>
public string DeQueue()
{
if (string.IsNullOrEmpty(queue[idxDeQueue])) { return ""; }
string buf = queue[idxDeQueue];
queue[idxDeQueue] = "";
idxDeQueue = (idxDeQueue + 1) % size;
return buf;
}
/// <summary>
/// キュー出力
/// </summary>
public string ExportQueue()
{
var queueFormat = new string[size];
this.queue.CopyTo(queueFormat, 0);
// EnQueue対象に[]を付ける
if (this.queue.Any(x => x != ""))
{
queueFormat[idxDeQueue] = $"[{queueFormat[idxDeQueue]}]";
}
return string.Join(", ", queueFormat);
}
}
}