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
59 lines
1.8 KiB
// The RecursiveMethods class that implements several recursive solutions
|
|
// Your name here
|
|
|
|
public class RecursiveMethods {
|
|
// This method calls the sumSquareRec method and returns the sum of the
|
|
// squares of the elements in the array.
|
|
public int sumSquares(int[] A) {
|
|
// Do not make any changes to this method!
|
|
return sumSquaresRec(A, 0);
|
|
}
|
|
|
|
// This method takes an integer array as well as an integer (the starting
|
|
// index) and returns the sum of the squares of the elements in the array.
|
|
public int sumSquaresRec(int[] A, int pos) {
|
|
|
|
int current_int = A[pos];
|
|
if (pos + 1 == A.length)
|
|
return current_int * current_int;
|
|
return current_int * current_int + sumSquaresRec(A, pos + 1);
|
|
}
|
|
|
|
// This method takes a character stack and converts all lower case letters
|
|
// to upper case ones.
|
|
public void upperStackRec(CharStack s) {
|
|
if (s.isEmpty())
|
|
return;
|
|
else {
|
|
char top = Character.toUpperCase(s.pop());
|
|
upperStackRec(s);
|
|
s.push(top);
|
|
}
|
|
}
|
|
|
|
// This method reads a string and returns the string in the reversed order.
|
|
public String reverseStringRec(String s) {
|
|
|
|
if (s.equals(""))
|
|
return s;
|
|
return reverseStringRec(s.substring(1)) + s.substring(0, 1);
|
|
|
|
}
|
|
|
|
// This method takes a reference to the head of a linked list.
|
|
// It returns the reference to the head of the linked list in the reversed order.
|
|
public LNode reverseListRec(LNode head) {
|
|
if (head == null)
|
|
return head;
|
|
if (head.getLink() == null)
|
|
return head;
|
|
|
|
LNode holder = reverseListRec(head.getLink());
|
|
LNode next = head.getLink();
|
|
|
|
next.setLink(head);
|
|
head.setLink(null);
|
|
return holder;
|
|
|
|
}
|
|
}
|