public class Solution {
/**
* Return a list containing, at most, the first numNodes nodes in the list starting with head. If
* numNodes is larger than the length of the list, then the entire list will be returned.
*
* Examples:
*
* <pre>
* [11, 12, 13], numNodes = 2
* returns [11, 12]
*
* [11, 12, 13], numNodes = 0
* returns []
*
* [11, 12, 13], numNodes = 100
* returns [11, 12, 13]
*
* [], numNodes = 5
* returns []
* </pre>
*
* @param head - Head of the list to truncate
* @param numNodes - Maximum number of nodes in the resulting list
* @return head of the truncated list
*/
public static ListNode truncate(ListNode head, int numNodes) {
// just return null
if (head == null) {
return null;
}
// Recursion head.next
if (head.next != null) {
head.next = truncate(head.next, numNodes--);
}
if (numNodes <= 0) {
return head.next;
} else {
return head;
}
}
如您所見,此代碼的目的是截斷 numNodes 之后的每個節點。除了通過長度為 4 的串列并且我需要回傳前 3 個節點(numNodes = 3)的情況之外,我還通過了所有測驗。如果有人可以幫助我,那將不勝感激。我不知道我做錯了什么。
這是 ListNode 類
/**
* Simple Singly-linked-list node.
*/
public class ListNode {
public int val;
public ListNode next;
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
public ListNode(int val) {
this.val = val;
this.next = null;
}
public ListNode() {
this.val = 0;
this.next = null;
}
}
這是我唯一失敗的測驗
testTruncateLengthFourListToThree() 預期:[10, 11, 12] 實際:[10, 11, 12, 13]
解決方案必須是遞回的。
uj5u.com熱心網友回復:
也許您可以在遞回呼叫 truncate 時使用前綴增量而不是后綴,從 truncate(head.next, numNodes--) 更改為 truncate(head.next, --numNodes) 以便 numNodes 在遞回之前遞減。
uj5u.com熱心網友回復:
嘗試這個。
record ListNode(int val, ListNode next) {}
public static ListNode truncate(ListNode head, int numNodes) {
if (head == null || numNodes <= 0)
return null;
else
return new ListNode(head.val, truncate(head.next, numNodes - 1));
}
public static String toString(ListNode head) {
List<String> list = new ArrayList<>();
for ( ; head != null; head = head.next)
list.add("" head.val);
return list.toString();
}
public static void main(String[] args) {
ListNode list = new ListNode(1, new ListNode(2, new ListNode(3, null)));
System.out.println("list = " toString(list));
System.out.println("truncate(list, 3) = " toString(truncate(list, 3)));
System.out.println("truncate(list, 2) = " toString(truncate(list, 2)));
System.out.println("truncate(list, 1) = " toString(truncate(list, 1)));
System.out.println("truncate(list, 0) = " toString(truncate(list, 0)));
}
輸出:
list = [1, 2, 3]
truncate(list, 3) = [1, 2, 3]
truncate(list, 2) = [1, 2]
truncate(list, 1) = [1]
truncate(list, 0) = []
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/310818.html
上一篇:Java中運算式的運算子優先級:11%2*7/(3 2)?[復制]
下一篇:Spring-bootmongodb-如何將MongoRepository保存回應轉換為自定義類并作為JSON回傳
