标签:代码实现 get 包括 代码 system img creates 方法 tor
递归书写方法:
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();
}
}
先将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
测试程序是否正确运行:
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)));
}
}
标签:代码实现 get 包括 代码 system img creates 方法 tor
原文地址:https://www.cnblogs.com/PyLearn/p/10013129.html