【问题标题】:inserting a node before another node with the same value in java在java中具有相同值的另一个节点之前插入一个节点
【发布时间】: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


【解决方案1】:

您忘记更新对链表第一个元素的引用。

见下方first = prev;

   // [...]

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 {
        // [...]
    }       
}

【讨论】:

  • 谢谢。那是我的问题忘了重新分配列表的头部。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-23
  • 2017-01-18
  • 2019-06-11
  • 2018-05-22
  • 2021-08-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多