Chapter 18 Exercise Set 1: Stack ApplicationsΒΆ
Write a function named
split_on_spacesthat takes a string as an argument and returns a vector of strings by separating the argument using spaces as the delimiter. The following doctests will make this task explicit:TEST_CASE("Test split_on_spaces") { vector<string> tokens = split_on_spaces("4 5 +"); CHECK(tokens.size() == 3); tokens = split_on_spaces("4 5 + 6 *"); CHECK(tokens.size() == 5); CHECK(tokens[0] == "4"); CHECK(tokens[1] == "5"); CHECK(tokens[2] == "+"); }
Write a Boolean function named
is_valid_infix_expressionthat takes a string containing a mathematical expression with+,-,*,/, and%operators, parentheses,(), for grouping, and numeric (digits) and variable (letters) operands, and returnstrueif the expression is valid andfalseif it is not.TEST_CASE("Test is_valid_infix_expression") { string expr = "(4 + a) / c" CHECK(is_valid_infix_expression(expr) == true); string expr = "(x * ((5 - d) + c) - y) * 2" CHECK(is_valid_infix_expression(expr) == true); string expr = "(x * ((5 - d) + c - y) * 2" CHECK(is_valid_infix_expression(expr) == false); }
Write a Boolean function named
has_matching_tagsthat takes a string containing HTML source and returnstrueif each open tag has a corresponding closing tag in the right place.Investigate the famous Towers of Hanoi puzzle, write a C++ program to print the steps to move a tower of size
nusing recursion (introduced in chapter 4 Recursion), and explain how this illustrates the relationship between stacks and recursion.