gpt4 book ai didi

java - 堆栈重新排列 堆栈奇数 偶数

转载 作者:行者123 更新时间:2023-12-02 05:09:17 28 4
gpt4 key购买 nike

我编写这个方法来重新排列两个堆栈的元素,使堆栈 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();
}

它工作得很好,但它也排序 ero ,我怎样才能消除 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,并且您的 if 情况是“非零且偶数”,您的 else 实际上是“零或奇数”。

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

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

关于java - 堆栈重新排列 堆栈奇数 偶数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27465853/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com