Practice #4
Coddyの「スタック - データ構造シリーズ #1」コースのレッスン 12/13。
最小/最大スタックを作成しましょう!
チャレンジ
簡単以前の Stack クラスに、次の2つの関数を追加してください:
min- 現在スタック内にある最小の数値を返します。max- 現在スタック内にある最大の数値を返します。
ボーナス: 各 push や pop のたびにスタック内のすべての要素を反復処理しないように工夫してみてください。
自分で試してみよう
#include <iostream>
#include <sstream>
#include <string>
#include "stack.h"
int main() {
Stack stack;
std::string line;
while (std::getline(std::cin, line)) {
std::istringstream iss(line);
std::string cmd;
if (!(iss >> cmd)) continue;
if (cmd == "push") {
int x; iss >> x; stack.push(x);
} else if (cmd == "pop") {
std::cout << stack.pop() << std::endl;
} else if (cmd == "top") {
std::cout << stack.top() << std::endl;
} else if (cmd == "size") {
std::cout << stack.size() << std::endl;
} else if (cmd == "min") {
std::cout << stack.min() << std::endl;
} else if (cmd == "max") {
std::cout << stack.max() << std::endl;
}
}
return 0;
}