You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
1.8 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. // The RecursiveMethods class that implements several recursive solutions
  2. // Your name here
  3. public class RecursiveMethods {
  4. // This method calls the sumSquareRec method and returns the sum of the
  5. // squares of the elements in the array.
  6. public int sumSquares(int[] A) {
  7. // Do not make any changes to this method!
  8. return sumSquaresRec(A, 0);
  9. }
  10. // This method takes an integer array as well as an integer (the starting
  11. // index) and returns the sum of the squares of the elements in the array.
  12. public int sumSquaresRec(int[] A, int pos) {
  13. int current_int = A[pos];
  14. if (pos + 1 == A.length)
  15. return current_int * current_int;
  16. return current_int * current_int + sumSquaresRec(A, pos + 1);
  17. }
  18. // This method takes a character stack and converts all lower case letters
  19. // to upper case ones.
  20. public void upperStackRec(CharStack s) {
  21. if (s.isEmpty())
  22. return;
  23. else {
  24. char top = Character.toUpperCase(s.pop());
  25. upperStackRec(s);
  26. s.push(top);
  27. }
  28. }
  29. // This method reads a string and returns the string in the reversed order.
  30. public String reverseStringRec(String s) {
  31. if (s.equals(""))
  32. return s;
  33. return reverseStringRec(s.substring(1)) + s.substring(0, 1);
  34. }
  35. // This method takes a reference to the head of a linked list.
  36. // It returns the reference to the head of the linked list in the reversed order.
  37. public LNode reverseListRec(LNode head) {
  38. if (head == null)
  39. return head;
  40. if (head.getLink() == null)
  41. return head;
  42. LNode holder = reverseListRec(head.getLink());
  43. LNode next = head.getLink();
  44. next.setLink(head);
  45. head.setLink(null);
  46. return holder;
  47. }
  48. }