在java中,在具有相同值的另一个节点之前插入一个节点
我试图递归地在链表中的给定值之前插入一个节点。我可以在列表中间的任何地方添加这个值,但是我很难在列表的开头添加一个节点。以下是我目前的代码:在java中,在具有相同值的另一个节点之前插入一个节点,java,data-structures,linked-list,nodes,Java,Data Structures,Linked List,Nodes,我试图递归地在链表中的给定值之前插入一个节点。我可以在列表中间的任何地方添加这个值,但是我很难在列表的开头添加一个节点。以下是我目前的代码: /** insertValueBeforeEveryX * * Preconditions: list may be empty, X and Value are not equal * * insert a new node containing Value before every node containing X *
/** 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);
}
输出:
成功{}.InsertValueBeforeVeryx1,99:结果:{}
失败{99}。InsertValueBeforeVeryx1,99:应为{1 99}实际{99}
成功{88}.InsertValueBeforeVeryx1,99:结果:{88}
失败{99 10}。InsertValueBeforeVeryx1,99:应为{1 99 10}实际{99 10}
成功{10 99}.InsertValueBeforeVeryx1,99:结果:{10 1 99}
失败{99 10 99}。InsertValueBeforeVeryx1,99:应为{1 99 10 1 99}实际{99 10 1 99}
成功{5 99 6 99 99 7}。InsertValueBeforeVeryx1,99:结果:{5 1 99 6 1 99 1 99 7}
如果您能帮我解释一下我做错了什么,我们将不胜感激。您忘了更新链接列表第一个元素的引用 见第一个=上一个;下面
您最好以迭代方式执行此操作,您需要检查当前节点的下一个节点是否具有该值,因为您需要在这两个节点之间放置一个新节点。我想我将尝试迭代。你并不是真的在帮助那些输入和期望已经发布的人谢谢你。这就是我的问题,我忘了重新分配名单的头号。
// [...]
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);
first = prev;
} else {
// [...]
}
}