Download presentation
Presentation is loading. Please wait.
1
Recursion & Linked Lists
2
Why Recursion & Linked Lists
Important for functional programming
3
Why Recursion & Linked Lists
Important for functional programming Important for more complex structures Linked Lists are good practice
4
Why Recursion & Linked Lists
Important for functional programming Important for more complex structures Linked Lists are good practice Can solve some problems better than iteration
5
Challenge How do we print this in reverse order?
6
Challenge Iterative: for(i = length-1 … 0) cout << retrieveAt(i)
How do we print this in reverse order? Iterative: for(i = length-1 … 0) cout << retrieveAt(i) BigO?
7
Challenge How do we print this in reverse order? Iterative: for(i = length-1 … 0) //O(n) cout << retrieveAt(i) //O(n) BigO? O(n2)
8
Challenge Better iterative: Make array of size n
Walk forward, adding items to array Print array backwards
9
Challenge Better iterative: Make array of size n
Walk forward, adding items to array O(n) Print array backwards O(n) 6 10 3 15
10
Challenge Recursive O(n) time Only call stack for storage
11
Recursive Setup Bookkeeping needed Pointer for position
Any other parameters current
12
Recursive Setup Recursive Function Needs Base case : General case :
I know my part of the answer without asking anyone else General case : I don’t know the whole answer, but here is one step
13
Print Print in forward order: Base case : If we hit nullptr, stop
14
Print Print in forward order: Base case : General case:
If we hit nullptr, stop General case: Print out current->data Recursively print rest
15
Print Print in forward order:
16
Print Print in forward order:
Non-member function kicks start recursion
17
getTotal getTotal: Base case : General case:
If at nullptr, answer is 0 General case: Current value + getTotal from all the rest
18
getTotal getTotal:
19
retireveAt retrieveAt(index) Base case : General case :
No steps left – return item General case : Ask “the next guy” to do one less step, return that
20
Strategy 1 removeLast removeLast Base Case : next to last node
If current->next->next == null Remove next General Case : Ask next to removeLast
21
Strategy 1 removeLast removeLast Base Case : next to last node
If current->next->next == null Remove next General Case : Ask next to removeLast What if only one item???
22
Strategy 2 removeLast removeLast Base Case : on last node
If current->next == null Delete current Return null General Case : Set current->next to result of removeLast on next Return current
23
removeLast Strategy 2 removeLast
24
removeLast Strategy 2 removeLast
25
removeLast Strategy 2 removeLast
26
removeLast Print in forward order:
Function always returns current or null Used to “fix up” node/head that was pointing to current
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.