【发布时间】:2020-05-17 02:58:56
【问题描述】:
我正在尝试递归地在链表中的给定值之前插入一个节点。我可以在列表中间的任何位置添加值,但我正在努力将节点添加到列表的开头。到目前为止,这是我的代码:
/** insertValueBeforeEveryX
*
* Preconditions: list may be empty, X and Value are not equal
*
* insert a new node containing Value before every node containing X
*
* you can write this iteratively or recursively, but you should only have one loop or recursive helper
* you may not call any other method (e.g. size )
*
* { }.insertValueBeforeEveryX(9,2) --> { } // initial list was empty
* { 1 1 1 1 }.insertValueBeforeEveryX(9,2) --> { 1 1 1 1 } // 0 occurrences of '2'
* { 2 }.insertValueBeforeEveryX(9,2) --> { 9 2} // 1 occurrence of '2'
* { 1 2 3 2 }.insertValueBeforeEveryX(9,2) --> { 1 9 2 3 9 2} // 2 occurrences of '2'
*
*/
public void insertValueBeforeEveryX (int value, int X ) {
insertValueBeforeEveryXHelper(first, value, X, null);
}
private void insertValueBeforeEveryXHelper(Node x, int val, int check, Node prev) {
if(x == null) return;
if(x.item == check && prev == null) {
prev = new Node(val, x);
} else {
if(x.item == check && prev != null) {
prev.next = new Node(val, x);
}
}
insertValueBeforeEveryXHelper(x.next, val, check, x);
}
输出:
Success { }.insertValueBeforeEveryX(1,99): Result: { }
Failed { 99 }.insertValueBeforeEveryX(1,99): Expecting { 1 99 } Actual { 99 }
Success { 88 }.insertValueBeforeEveryX(1,99): Result: { 88 }
Failed { 99 10 }.insertValueBeforeEveryX(1,99): Expecting { 1 99 10 } Actual { 99 10 }
Success { 10 99 }.insertValueBeforeEveryX(1,99): Result: { 10 1 99 }
Failed { 99 10 99 }.insertValueBeforeEveryX(1,99): Expecting { 1 99 10 1 99 } Actual { 99 10 1 99 }
Success { 5 99 6 99 99 7 }.insertValueBeforeEveryX(1,99): Result: { 5 1 99 6 1 99 1 99 7 }
任何帮助解释我做错了什么将不胜感激。
【问题讨论】:
-
您最好迭代地执行此操作,您需要检查当前节点的下一个节点具有该值的情况,因为您需要在这两个节点之间放置一个新节点。
-
我想我会尝试迭代。你并没有真正帮助你
-
输入和预期已经发布
标签: java data-structures linked-list nodes