从堆栈中返回偶数?

时间:2016-06-01 09:36:22

标签: java stack

如何传递一个整数堆栈,它返回偶数的数量。方法完成执行后,堆栈必须保持不变。如果堆栈为空,则返回null。

这是我到目前为止所做的,对不起我是初学者。

public static int countEven(Stack<Integer> stk) {

        Stack stack = new stack();
        int count = 0;

        while (int i=0; i<stack.length; i++);        
            int value = s.pop();

            if (stack %2 == 0);                       
                count++;

            stack.push(value);

        while (int i=0; stack != 0; i++);
            s.push(stack.pop());

    return 0;
}

3 个答案:

答案 0 :(得分:0)

你在模2上检查堆栈?您必须检查堆栈中的值。 你也可以使用“get”函数。它只给你堆栈中的值(对于给定的索引)而不删除它。

如果返回整数,则不能返回null。只需返回-1 ......

public static int countEven(Stack<Integer> stk) {

    int count = 0;
    if (stk.size() == 0) 
        return -1;

    while (int i=0; i<stk.size(); i++) {
        int value = stk.get(i);
        if (value %2 == 0)                       
            count++;
    }    

    return count;
}

答案 1 :(得分:0)

您无需从堆栈中删除元素。您可以获得Iterator并迭代所有元素并处理您的支票。

你的方法看起来像。

static int countEven(Stack<Integer> stack) {
    // get an Iterator for the passed stack
    Iterator<Integer> iterator = stack.iterator();
    int count = 0;
    // as long the iterator would return another element process the loop
    while (iterator.hasNext()) {
        // check if the integer is even
        if (iterator.next() % 2 == 0) {
            // increase the even counter
            count++;
        }
    }
    // return the count, if there was no element returned by the iterator
    // `count` would not have been incremented and therefor return zero
    return count;
}

答案 2 :(得分:0)

您不需要修改堆栈或使用其他堆栈来使用java.util.Stack获取所有元素

Stack扩展了Vector,因此您可以使用get(int)

public static int countEven(Stack<Integer> stack) {
    // Return 0 if the stack is empty
    if (stack == null || stack.isEmpty()) {
        return 0;
    }

    int count = 0;
    int size = stack.size();

    for (int i = 0; i < size; i++) {        
        int value = stack.get(i); // get ith element
        if (value % 2 == 0)                       
            count++;
    }

    return count;
}

由于您不熟悉Java,我建议您学习一些关于Java的基础知识。 您可以在TutorialsPoint

上参考本教程
相关问题