【问题标题】:Advice needed: What and how to removeNulls (I'm not sure exactly what to do)需要的建议:什么以及如何删除 Nulls(我不确定该怎么做)
【发布时间】:2015-02-26 00:20:02
【问题描述】:

我在讲座中有一个练习题,我不确定如何解决,希望能深入了解应该做什么并给出解释:

Q:给出方法 removeNulls(q) 的代码,该方法从队列 q 中删除所有空元素。方法 main 包含一个简单的示例,说明方法 removeNulls 的效果。

    package labsSGTsCoursework.cw1;
     import net.datastructures.NodeQueue;
     import net.datastructures.Queue;
     public class CW1_q4 {
        public static <E> void removeNulls( Queue<E> q) {
             ... // YOUR CODE REPLACES DOTS HERE
}
        public static void main(String[] args) {
           // test method removeNulls
           Queue<Integer> que = new NodeQueue<Integer>();
           que.enqueue(5);
           que.enqueue(null);
           que.enqueue(8);
           que.enqueue(2);
           que.enqueue(null);
           System.out.println(que); // should print: "(5, null, 8, 2, null)"
           removeNulls(que);
           System.out.println(que); // should print: "(5, 8, 2)"
         }
}

【问题讨论】:

  • 遍历Queue...?
  • Iterator 怎么样,E next() 返回迭代中的下一个元素,remove() ?

标签: java database data-structures removeclass


【解决方案1】:

对不起,我没有注意到它是通用的,所以标记方法不起作用(有时认为这是一个有用的技巧,所以我把它留在下面)。

在方法内部,创建一个新队列,将所有非空值从旧队列复制到新队列,然后返回到原始队列(因为这些值是从原始队列中消耗的,因此您需要将它们放回原处)。

不是,通用方法,标记方法可能会起作用(只要某些值永远不会出现在输入中): 插入一个标记,例如 Integer.MAX_VALUE,遍历 que 并插入所有不为空的元素,一旦遇到标记就停止。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-07
    • 1970-01-01
    • 1970-01-01
    • 2012-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多