java 练习递归..计算负值
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 练习递归..计算负值相关的知识,希望对你有一定的参考价值。
import java.io.*;
import java.util.*;
// Recursion practice
class Solution {
class Node {
int value;
Node next;
Node(int value, Node next){
this.value = value;
this.next = next;
}
public void print(){
System.out.print(this.value + ",");
if(this.next != null) {
this.next.print();
}
}
}
public static void main(String[] args) {
Solution solution = new Solution();
int[][] input = {
{-1,2,-41,4,-8},
{1,3,-9,121,31},
{1,1,1}
};
for(int i=0; i< input.length; i++){
Node root = solution.createList(input[i]);
System.out.print("Input :");
root.print();
System.out.print(" ResultI: " + solution.countNeg(root));
System.out.print(", ResultR: " + solution.countNegR(root));
System.out.print(", ResultRH: " + solution.countNegRH(root));
System.out.println();
}
}
public Node createList(int[] input){
Node root = null;
for(int i=input.length-1;i>=0;i--){
Node newNode = new Node(input[i], root);
newNode.next = root;
root = newNode;
}
return root;
}
public int countNeg(Node root){
Node runner = root;
int count = 0;
while(runner != null) {
if(runner.value < 0){
count++;
}
runner = runner.next;
}
return count;
}
public int countNegR(Node root) {
if(root == null){
return 0;
}
int current = 0;
if(root.value < 0){
current = 1;
}
return current + countNeg(root.next);
}
public int countNegRH(Node root) {
if(root == null){
return 0;
}
int count = countNeg(root.next);
if(root.value < 0){
count += 1;
}
return count;
}
}
以上是关于java 练习递归..计算负值的主要内容,如果未能解决你的问题,请参考以下文章
leetcode递归练习总结
[PTA]练习10-1 使用递归函数计算1到n之和
02方法-作业01-递归练习
练习10-1 使用递归函数计算1到n之和(10 分
OI入门
JAVA基础24 递归练习