Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 堆栈重设堆栈奇偶范围_Java_Stack - Fatal编程技术网

Java 堆栈重设堆栈奇偶范围

Java 堆栈重设堆栈奇偶范围,java,stack,Java,Stack,我编写这个方法是为了重新排列两个堆栈的元素,使堆栈s1只包含偶数整数,而堆栈s2只包含奇数整数。任何零都不应存储在s1或s2中 public static void rerange(stackl l1 , stackl l2) { stackl tmp = new stackl(); stackl tmp2 = new stackl(); while(!l1.isEmptyS()) { int x = l1.pop(); if(x

我编写这个方法是为了重新排列两个堆栈的元素,使堆栈s1只包含偶数整数,而堆栈s2只包含奇数整数。任何零都不应存储在s1或s2中

public static void rerange(stackl l1 , stackl l2)
{
    stackl tmp = new stackl();
    stackl tmp2 = new stackl();
    while(!l1.isEmptyS()) 
    {
        int x = l1.pop();
        if(x!=0 && x%2==0)
            tmp.push(x);
        else 
            tmp2.push(x);
    }
    while(!l2.isEmptyS())
    {
        int y = l2.pop();
        if(y!=0 && y%2==0)
            tmp.push(y);
        else 
            tmp2.push(y);
    }
    tmp.prints();
    System.out.println();
    tmp2.prints();
}
它工作得很好,但也很好,如何消除0

这里是主要的方法

  public static void main(String[] args) {
        stackl s1 = new stackl();
        stackl s2 = new stackl();
        s1.push(0);
        s1.push(2);
        s1.push(3);
        s1.push(5);
        s1.push(6);
        s1.prints();
        System.out.println();
        s2.push(1);
        s2.push(10);
        s2.push(9);
        s2.push(0);
        s2.push(15);
        s2.prints();
        System.out.println();
        rerange(s1,s2);
输出为:

6 5 3 2 0 
15 0 9 10 1 
10 2 6 
1 9 0 15 0 3 5

由于您编写if语句的方式,您的代码将零放入奇数堆栈中:

if (x != 0 && x % 2 == 0)
    // x is non-zero and even
    tmp.push(x);
else
    // all other numbers (x is zero, or odd)
    tmp2.push(x);
当您在初始检查中将这两个条件合并在一起时,else将选择否定的条件。
因为逻辑上
!(A和B)
!A | | |!B
,如果您的案例是“非零且偶数”,那么您的else实际上是“零或奇数”

您需要做的是首先检查零度,在这种情况下不要推动任何东西:

if (x != 0) {
    if (x % 2 == 0) {
        tmp.push(x);
    } else {
        tmp2.push(x);
    }
}