AOJ本の読書メモ
AOJ
次のAOJの問題へ
前のAOJの問題へ
ALDS1_3_A: Stack
C#のソース
using System;
using System.Collections.Generic;
using System.Linq;
// Q007 スタック https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_3_A&lang=jp
class Program
{
static string InputPattern = "InputX";
static List<string> GetInputList()
{
var WillReturn = new List<string>();
if (InputPattern == "Input1") {
WillReturn.Add("1 2 + 3 4 - *");
//-3
}
else {
string wkStr;
while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
}
return WillReturn;
}
static void Main()
{
List<string> InputList = GetInputList();
string[] RPNArr = InputList[0].Split(' ');
var Stk = new Stack<int>();
foreach (string EachStr in RPNArr) {
if (EachStr == "+" || EachStr == "-" || EachStr == "*") {
int exp2 = Stk.Pop();
int exp1 = Stk.Pop();
if (EachStr == "+") Stk.Push(exp1 + exp2);
if (EachStr == "-") Stk.Push(exp1 - exp2);
if (EachStr == "*") Stk.Push(exp1 * exp2);
continue;
}
Stk.Push(int.Parse(EachStr));
}
Console.WriteLine(Stk.Pop());
}
}
解説
Stackジェネリックを使ってます。