C# Stack and Queue: evaluating postfix expressions
Stack<T> is last-in, first-out with Push, Pop, and Peek. Queue<T> is first-in, first-out with Enqueue and Dequeue. Both operations are O(1). Popping from an empty stack or queue throws InvalidOperationException.
C#
using System;
using System.Collections.Generic;
class Program {
static int EvalPostfix(string expression) {
var stack = new Stack<int>();
foreach (string token in expression.Split(' ')) {
if (int.TryParse(token, out int number)) {
stack.Push(number);
} else {
int right = stack.Pop();
int left = stack.Pop();
stack.Push(token switch {
"+" => left + right,
"-" => left - right,
"*" => left * right,
"/" => left / right,
_ => throw new ArgumentException("bad operator " + token),
});
}
}
return stack.Pop();
}
static void Main() {
Console.WriteLine(EvalPostfix("3 4 + 2 *"));
Console.WriteLine(EvalPostfix("5 1 2 + 4 * + 3 -"));
try {
EvalPostfix("2 3 ^");
} catch (ArgumentException e) {
Console.WriteLine(e.Message);
}
var line = new Queue<string>();
line.Enqueue("Ada");
line.Enqueue("Bo");
line.Enqueue("Cy");
Console.WriteLine(line.Dequeue() + " served, " + line.Count + " waiting, next is " + line.Peek());
}
}