Download presentation
Presentation is loading. Please wait.
Published byJames Garrison Modified over 9 years ago
1
Duke CPS 100 4. 1 Recursion l Often phrased as “a function calls itself” ä function actually calls a clone, not itself ä each clone has its own variables/parameters/state ä when a clone is finished, execution continues with the function that called the clone (may be a …) l Recursion is useful in solving lots of problems, but should be avoided on occasion ä lots of function calls, clones made ä total # of clones called vs # in existence at one time ä see Fibonacci (bad) and logarithmic power (good)
2
Duke CPS 100 4. 2 Rules of recursion l There must be a base case, no recursive calls l Each call must make progress towards the base case ä call is similar, but simpler int CountNodes(Node * list) { if (list == 0) return 0; else return 1 + CountNodes(list->next); } l Make the recursive call, use the result to determine what to do/what to return ä something has happened as result of recursion
3
Duke CPS 100 4. 3 Reading words (yet again) Node * ReadWords(istream & input) //pre: input readable //post: returns linked list of words in input,in order { string word; if (input >> word) { return new Node(word, ReadWords(input)); } return 0; // make sure list is terminated! } l Node has a constructor, what does it look like? ä how many parameters? ä default values?
4
Duke CPS 100 4. 4 Recursion and Reading l What to return when no words left? l Each call returns a complete list struct Node { string info; Node * next; Node(const string & s, Node * link = 0) : info(s), next(link) { } }; ReadWords(input) after one word one word left no words left
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.