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]
解决方案必须是递归的。