递归控制-创建链表

0.目录

1.递归控制

2.Java代码实现

1.递归控制

递归书写方法:

  • 严格定义递归函数作用,包括参数,返回值,Side-effect
  • 一般,后特殊
  • 每次调用 必须 缩小问题规模
  • 每次问题规模缩小程度必须为 1

2.Java代码实现

2.1 链表结点的实现

Node有两个成员:
一个是value,希望用户创建后就不要修改了;
还有一个是next,创建时默认指向null。

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

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

    public int getValue() {
        return value;
    }

    public Node getNext() {
        return next;
    }

    public void setNext(Node next) {
        this.next = next;
    }

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

2.2 创建链表的实现

先将data中第一个数拿出来建立一个firstNode,
然后firstNode指向剩下的data建立的链表的head,
最后返回firstNode

    /**
     * Creates a Linked list.
     *
     * @param data the data to create the list
     * @return head of the linked list. The returned linked
     * list ends with last node with getNext() == null.
     */
    public Node createLinkedList(List<Integer> data) {
        if (data.isEmpty()) {
            return null;
        }

        Node firstNode = new Node(data.get(0));
        firstNode.setNext(
            createLinkedList(data.subList(1, data.size())));
        return firstNode;
    }

注:当data只有1个元素时 data.subList(1, data.size()) 返回null

2.3 测试用例

测试程序是否正确运行:

    public static void main(String[] args) {
        LinkedListCreator creator = new LinkedListCreator();

        Node.printLinkedList(
            creator.createLinkedList(new ArrayList<>()));
        Node.printLinkedList(
            creator.createLinkedList(Arrays.asList(1)));
        Node.printLinkedList(
            creator.createLinkedList(Arrays.asList(1, 2, 3, 4, 5)));
    }

运行结果为

main所在java文件全部代码:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class LinkedListCreator {

    /**
     * Creates a Linked list.
     *
     * @param data the data to create the list
     * @return head of the linked list. The returned linked
     * list ends with last node with getNext() == null.
     */
    public Node createLinkedList(List<Integer> data) {
        if (data.isEmpty()) {
            return null;
        }

        Node firstNode = new Node(data.get(0));
        firstNode.setNext(
            createLinkedList(data.subList(1, data.size())));
        return firstNode;
    }

    public static void main(String[] args) {
        LinkedListCreator creator = new LinkedListCreator();

        Node.printLinkedList(
            creator.createLinkedList(new ArrayList<>()));
        Node.printLinkedList(
            creator.createLinkedList(Arrays.asList(1)));
        Node.printLinkedList(
            creator.createLinkedList(Arrays.asList(1, 2, 3, 4, 5)));
    }
}
posted @ 2018-11-24 19:26  PyLearn  阅读(651)  评论(0编辑  收藏  举报