Data Structures and Algorithms Sheet #4 Recursion: Part I: Exercises
Data Structures and Algorithms Sheet #4 Recursion: Part I: Exercises
Cairo University
Faculty of Engineering
Computer Engineering Department
Data Structures and Algorithms
Sheet #4
Recursion
Part I: Exercises
5. Does it matter where you position your recursive call in your function?
Given two versions of recursive function that searches for a given value in a linked list; what
is the difference between the two functions? Which one is better and why?
Test the two functions if linked list L = [10]→[12] → [4]→[7]→[56]→[9]→# and val=12.
Node* RecSearch1(Node *L, int val) Node* RecSearch2(Node *L, int val)
{ {
if(L == NULL) return NULL; if(L == NULL) return NULL;
if(L->data == val) return L;
Node *P = RecSearch2(L->Next, val);
return RecSearch1(L->Next, val); if( P != NULL) return P;
} if(L->data == val) return L;
else return NULL;
}
3. Write a recursive algorithm that calculates and returns the sum of array elements.
5. Write a recursive algorithm that calculates and returns the length of a linked list.
6. Write a recursive algorithm to compute the sum of even numbers in a linked list.
7. Write a recursive algorithm to print a linked list in a forward order. What are the modifications to print
it reversed?
8. Write a recursive algorithm to print numbers read from keyboard in a forward order. What are the
modifications to print them reversed? (Note: don’t store numbers in an array; just print)
9. Compare the recursive solution of print reverse of problem 7 and 8 with the stack solution.
10. Compare the recursive solution of print forward of problem 7 and 8 with the iterative solution.
11. Write a recursive algorithm that returns the index of the first occurrence of an element in array if
found and -1 if not found. What are the modifications to return the index of last occurrence?
12. Write a recursive algorithm to check whether a linked list is sorted in an increasing order.
13. Write a recursive algorithm that checks whether a string is a substring of another string.
14. Write a recursive algorithm that converts a string of numerals to an integer. For example, “43567” will
be converted to 43567. (Hint: 43567 = 4*10000+3*1000+5*100+6*10+7*1)
15. Write a recursive C++ function to get the length of a circular linked list (Hint: you should send the
head of the original list too in each call; 2 inputs)
16. Write a recursive algorithm that reverses a linked list (without using new nodes). (Hint: make each
next pointer points to previous. It’s simple if you think recursively)
17. Solve palindrome problem (stack problem 2, sheet 4) using recursion. (Hint: check the first
character with the last character)