List of all available Websheets
Viewing cpp/recursion/list_max by redekopp@usc.edu. You have unsaved changes. Log in above to create, edit, preview and publish Websheets.
Property | Value |
---|---|
Description html markup shown to student | <p> Using recursion, create a method <tt>maximum()</tt> that finds the maximum element in a linked list of integers. You will need to declare and define a helper function. </p> <p>You may use <tt>std::max(int, int)</tt> in your solution, but realize it only finds the max of two integers. </p> |
Public permissions | |
Engine | |
Template / Reference solution |
using namespace std; // structure of items in list struct Node { Node* next; // each node knows "next" node int value; Node(int initialValue); // constructor for nodes }; Node::Node(int initialValue) {value = initialValue; next = NULL;} class IntChain { public: IntChain(); int maximum(); void addStart(int newValue); private: \[ int helpMax(Node* n); // compute max from here to end ]\ Node* head; }; IntChain::IntChain() {head = NULL;} \hide[ // add a new node, containing this name, at the start of the list void IntChain::addStart(int newValue) { Node* newFirst = new Node(newValue); Node* oldFirst = head; head = newFirst; head->next = oldFirst; // there's also a slightly trickier 2-line solution } ]\ // private helper \[ int IntChain::helpMax(Node* n) { if (n->next == NULL) { return n->value; // nothing to reverse } else { return max(n->value, helpMax(n->next)); } } ]\ int IntChain::maximum() { \[ return helpMax(head); ]\ } int main() { IntChain c; int x; while (cin >> x) c.addStart(x); cout << c.maximum(); } |
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 [{}] | [ {"stdin": "1 0 3"}, {"stdin": "3 0 1"}, {"stdin": "1 3 0"}, {"stdin": "9 4 4 0 19"}, {"stdin": "2923 2 20 43 298"} ] |
Forbidden substrings json list of strings e.g. ["for","while"] | ["for", "while", "do"] |
Solution visibility |
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'.