递归求和
public class Sum {
public static int sum(int [] arr)
{
return sum(arr,0);
}
private static int sum(int [] arr,int index)
{
if(index==arr.length)
{
return 0;
}
return arr[index]+sum(arr,index+1);
}
public static void main(String[] args) {
int[] nums = {1, 2, 3, 4, 5, 6, 7, 8};
System.out.println(sum(nums));
}
}
链表删除元素递归实现
public class Solution4 {
public ListNode removeElements(ListNode head, int val) {
if (head == null) {
return head;
}
ListNode res = removeElements(head.next, val);
if (head.val == val) {
return res;
} else {
head.next = res;
return head;
}
}
public static void main(String[] args) {
int[] nums = {1, 2, 6, 3, 4, 5, 6};
ListNode head = new ListNode(nums);
System.out.println(head);
ListNode res = (new Solution4()).removeElements(head, 6);
System.out.println(res);
}
}
运行机制