遞迴控制-建立連結串列
阿新 • • 發佈:2018-11-24
0.目錄
1.遞迴控制
2.Java程式碼實現
- 2.1 連結串列結點的實現
- 2.2 建立連結串列函式的實現
- 2.3 測試用例
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)));
}
}