创建列表:
1、严格定义函数:给入一个数组,把数组里的每一个元素生成一个节点,然后让节点首尾相接,链表以null结尾,链表必须第一个结点点作为链表头。
2、先一般后特殊,定义函数Node CreateLinkedList(List<Integer> values)
3、每次调用必须缩小问题规模
4、每次问题规模缩小程度必须为1
把1拆掉,把2,3,4,5建立一个链表
再把1接上
1和2,3,4,5链表接起来的过程:
把1的next指向2,3,4,5这个链表所返回的头结点就完成这个链表的创建。
代码示例:
package com.sise.recursion;
public class Node {
private final int value;//用户定义之后就不能修改
private Node next;
public Node(int value){
this.value=value;
this.next=null;//这样建立出来的结点都是单点Node
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public int getValue() {
return value;
}
//打印函数
public static void printLinkedList(Node head) {
while(head!=null){
System.out.print(head.getValue());;
System.out.print(" ");
head=head.getNext();
}
System.out.println();
}
}
package com.sise.recursion;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class LinkedListCreator {
/*
* 创建一个链表
* @return 链表的头结点,返回链表的最后一个结点的getNext()==null.
*/
public Node createLinkedList(List<Integer> data){
//假设传入空的List(这是特殊处理部分)
if(data.isEmpty()){
return null;
}
//取出传入数据的第一个结点
Node firstNode=new Node(data.get(0));
//取走一个元素后,从第二个元素创建一个链表,
//因为返回的是Node,所以用Node来接收
//假设传入来的List有一个元素,则走到这里时sublist传入的两个参数相等
//但是sublist函数的定义可以看到fromIndex==toIndex时,返回null
/*
* <tt>fromIndex</tt> and <tt>toIndex</tt> are equal, the returned list is
*/
//与我们期望返回值一致
// Node headOfSublistNode=
// createLinkedList(data.subList(1, data.size()));
// //第一个结点的next指向规模缩小的链表返回来的头结点
// firstNode.setNext(headOfSublistNode);
//上面两行代码清理成如下代码
firstNode.setNext(createLinkedList(data.subList(1, data.size())));
return firstNode;
}
public static void main(String[] args) {
LinkedListCreator creator=new LinkedListCreator();
ArrayList arrayList=new ArrayList<>();
Node.printLinkedList(
creator.createLinkedList(arrayList)
);
Node.printLinkedList(
creator.createLinkedList(Arrays.asList(1))
);
Node.printLinkedList(
creator.createLinkedList(Arrays.asList(1,2,3,4,5))
);
}
}
运行结果: