Create a list by recursively

Recursion is a kind of mathematically coded mathematical induction .

Specialization: When 1:00 establishment n == (in the code is not necessarily a special case n == 1, could n == 0, or n == null), generalized process sometimes affect special circumstances. So when writing the code should try to finish first generalized logical process again consider specialization.

Generalization: For n-1 established a relationship, for n also established (in writing program) mathematics is n-1 satisfy a relationship n confirmation also satisfied.

For chestnut:

The following two recursive summation function is right, but different

// generalized different result in different specialized 
int SUM ( int n-) { // find a natural number and 1 ~ n 
IF (n-== . 1 ) return  . 1 ; // particularized 
return SUM (N- . 1 ) + n-; /// generalized 
} 
int SUM1 ( int n-) { // find a natural number and 1 ~ n IF (n-== . 1 ) return . 1 ; // specialize IF (n-== 2 ) return . 3 ; return SUM (N- 2 ) + + n-N- . 1; // generalization }

 

 java代码如下:
节点类定义:

package interview;

public class Node {
private final int value;
private Node next;

public Node(int value) {
    super();
    this.value = value;
    this.next = null;
}
public Node getNext() {
    return next;
}

public void setNext(Node next) {
    this.next = next;
    
}
public int getValue() {
    return value;
}

public static void printList(Node head){
while(head!=null){
    System.out.print(head.getValue());
    System.out.print(" ");
    head=head.getNext();    
}System.out.println();
}


}

主函数:

package interview;

import java.util.List;
import java.util.Arrays;
public class list {
    /**
     * Creats a Linked List    
     * 
     * @param data the data to creat the list
     * @return head of the linked list.The return linked list 
     * ends with last node with getNext() == null.
     */
    public Node creatList(List<Integer> data){
    
        if(data.isEmpty()){
            return null;
        }
        Node firstNode = new Node(data.get(0));
        Node headofSublist = creatList(data.subList(1,data.size()));
        firstNode.setNext(headofSublist);
        return firstNode;
        
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        list creator = new list();
        //Node.printList(new ArrayList<>());
        Node.printList(creator.creatList(Arrays.asList(1)));
        Node.printList(creator.creatList(Arrays.asList(1,2,3,4,5)));
        
        

    }

}

 

Guess you like

Origin www.cnblogs.com/cstdio1/p/11250359.html