Not logged in. Log in with GitHub. About Websheets.

List of all available Websheets


Viewing cpp/recursion/monkey_recback by redekopp@usc.edu. You have unsaved changes. Log in above to create, edit, preview and publish Websheets.
PropertyValue
Description
html markup
shown to student
 
Using recursion,
create a method <tt>printBackwards()</tt>
that prints out all names in the list, one per line, <b>in reverse order</b>.
You will need to declare and define a helper function.
Public permissions remove
Engine
Template / Reference solution
 
#include <iostream>
#include <string>
using namespace std;
// structure of items in list
struct Node {
   Node* next;  // each node knows "next" node
   string name; // and stores a value
   Node(string initialName);  // constructor for nodes
};
Node::Node(string initialName) {name = initialName; next = NULL;}
class MonkeyChain {
   public:
      MonkeyChain();
      void threeKongs();
      void printBackwards();
      void addStart(string newName); // implementation not shown
   private: 
\[
      void helpPrintBackwards(Node* n);
]\
      Node* head;
};
\hide[
// add a new node, containing this name, at the start of the list
void MonkeyChain::addStart(string newName) {
   Node* newHead = new Node(newName);
   Node* oldHead = head;
   head = newHead;
   head->next = oldHead;
   // there's also a slightly trickier 2-line solution
}
]\
MonkeyChain::MonkeyChain() {head = NULL;}
// a demo to create a length-3 list
void MonkeyChain::threeKongs() {
   head = new Node("DK Sr.");
   head->next = new Node("DK");
   head->next->next = new Node("DK Jr.");
}
// private helper
void MonkeyChain::helpPrintBackwards(Node* n) {
\[
   if (n != NULL) {
      helpPrintBackwards(n->next);
      cout << n->name << endl;
   }
]\
}
void MonkeyChain::printBackwards() {
\[
   helpPrintBackwards(head);
]\
}
int main() {
   MonkeyChain mc;
   mc.threeKongs();
   mc.printBackwards(); cout << endl;
   // test on 5 monkeys
   mc.addStart("King Kong");
   mc.addStart("Bubbles");
   mc.printBackwards(); 
}
C++ test suite
json list of stdin/args tests
e.g. [{"stdin":"hi", "args":["4", "5"]},
{"stdin":"noargs"}]

to just run once with no input use [{}]
 
[
   {}
]
Forbidden substrings
json list of strings
e.g. ["for","while"]
 
["for", "while", "do"]
remove
Solution visibility remove


Optional properties:

Note: problems are open-source by default (see 'Public permissions'). Assumed license for open problems is Creative Commons 4.0 Attribution-ShareAlike unless specified in 'Remarks'.