Embercode
✕
Stacks and QueuesQuick quiz

Shunting-yard

7 questions. Covers Infix to postfix with the shunting-yard method.

Questions 1 to 5 of 7

  1. 1. The shunting-yard method turns a - b - c into postfix. Which output does it give?
  2. 2. In the shunting-yard method, which kind of token never goes to the output?
  3. 3. What does this program print? ``cpp #include <cstddef> #include <iostream> #include <stack> #include <string> #include <vector> int precedence(char op) { if (op == '*' || op == '/') return 2; if (op == '+' || op == '-') return 1; return 0; } int main() { const std::vector<std::string> tokens = {"2", "*", "3", "+", "4", "-", "5"}; std::vector<std::string> output; std::stack<char> ops; for (const std::string& tok : tokens) { if (tok == "+" || tok == "-" || tok == "*" || tok == "/") { const char op = tok[0]; while (!ops.empty() && ops.top() != '(' && precedence(ops.top()) >= precedence(op)) { output.push_back(std::string(1, ops.top())); ops.pop(); } ops.push(op); } else { output.push_back(tok); } } while (!ops.empty()) { output.push_back(std::string(1, ops.top())); ops.pop(); } for (std::size_t i = 0; i < output.size(); ++i) { std::cout << (i ? " " : "") << output[i]; } std::cout << '\n'; } ``
  4. 4. What does this program print? ``cpp #include <cstddef> #include <iostream> #include <stack> #include <string> #include <vector> int precedence(char op) { if (op == '*' || op == '/') return 2; if (op == '+' || op == '-') return 1; return 0; } int main() { const std::vector<std::string> tokens = {"9", "/", "3", "/", "3"}; std::vector<std::string> output; std::stack<char> ops; for (const std::string& tok : tokens) { if (tok == "+" || tok == "-" || tok == "*" || tok == "/") { const char op = tok[0]; while (!ops.empty() && ops.top() != '(' && precedence(ops.top()) >= precedence(op)) { output.push_back(std::string(1, ops.top())); ops.pop(); } ops.push(op); } else { output.push_back(tok); } } while (!ops.empty()) { output.push_back(std::string(1, ops.top())); ops.pop(); } for (std::size_t i = 0; i < output.size(); ++i) { std::cout << (i ? " " : "") << output[i]; } std::cout << '\n'; } ``
  5. 5. Put these steps for an operator token in the order the method does them.

    Use the arrows to put the steps in order.

    1. 1.Pop each operator on top of the stack that binds at least as tightly, writing it to the output
    2. 2.Push the new operator onto the stack
    3. 3.Stop popping at an opening bracket or at an operator that binds less tightly
    4. 4.Read the operator token from the input

4 question(s) left on this page.