好了,伙计们,这是我最新的密码。这就是我所拥有的。我需要堆栈保持原始数字,我需要堆栈2,3和4来保持它们的原始数字,现在我得到的只是1s2s和0s。
进口java.util.Random;
public class Lab5
{
public static void main(String[] arg)
{
Random rnd = new Random();
Stack<Integer> stack = new IStack<Integer>();
Stack<Integer> stack2= new IStack<Integer>();
Stack<Integer> stack3= new IStack<Integer>();
Stack<Integer> stack4= new IStack<Integer>();
int stream,y;
for(int i=0;i<20;i++)
{
stream = rnd.nextInt(101);
stack.push(stream);
// stack2.push(stream);
}
for(int i=0; i<20; i++)
{
int x = stack.pop()%3;
if(x == 0%3)
stack2.push(x);
if(x == 1%3)
stack4.push(x);
if(x == 2%3)
stack3.push(x);
}
while( !stack.isEmpty() )
System.out.print(stack.pop()+" ");
System.out.println();
while( !stack2.isEmpty() )
System.out.print(stack2.pop()+" ");
System.out.println();
while( !stack3.isEmpty() )
System.out.print(stack3.pop()+" ");
System.out.println();
while( !stack4.isEmpty() )
System.out.print(stack4.pop()+" ");
System.out.println();
}
}发布于 2014-10-20 17:47:32
我想我们提出的解决方案越多,就会出现更多的限制。首先,直截了当的解决方案是跳过流行阶段,一开始就把所有的堆栈填入其中:
for(int i=0;i<20;i++) {
final int value = rnd.nextInt(101), x=value%3;
stack.push(value);
if(x == 0) stack2.push(x);
else if(x == 1) stack4.push(x);
else if(x == 2) stack3.push(x);
}如果有一个流行阶段是必需的,您可以利用堆栈实际上已经过时的事实来存储许多相同的值;一个简单的计数器就足够了:
for(int i=0;i<20;i++)
stack.push(rnd.nextInt(101));
int numberOfZeros=0;
while(!stack.isEmpty()) {
int value = stack.pop(), x = value % 3;
if(x == 0) numberOfZeros++;
else if(x == 1) stack4.push(x);
else if(x == 2) stack3.push(x);
stack2.push(value);// use stack2 as temporary storage
}
while(!stack2.isEmpty()) stack.push(stack2.pop()); // transfer back
for(;numberOfZeros>0; numberOfZeros--) stack2.push(0);最后,以下是最有可能让你的老师高兴的学术解决方案:
创建一个递归助手函数:
static void fillOtherStacks(Stack<Integer> from,
Stack<Integer> stack2, Stack<Integer> stack3, Stack<Integer> stack4) {
int value = from.pop(), x = value % 3;
if(x == 0) stack2.push(x);
else if(x == 1) stack4.push(x);
else if(x == 2) stack3.push(x);
if(!from.isEmpty())
fillOtherStacks(from, stack2, stack3, stack4);// process the rest of stack
from.push(value); // and push back the value
}并使用它
for(int i=0;i<20;i++)
stack.push(rnd.nextInt(101));
fillOtherStacks(stack, stack2, stack3, stack4);所有解决方案都使用纯堆栈操作pop、push和isEmpty,您的自定义Stack必须实现这些操作。
发布于 2014-10-20 15:35:30
for(int i=0;i<21;i++)
{
stream = rnd.nextInt(101);
stack.push(stream);
stack2.push(stream);
}在这段代码之后,您的stack2包含21个Ints。
但当你这么做的时候
for(int i=0; i<21;i++)
{
int x = stack2.pop();
if(stack2.pop()== 0%3) ....它每个循环删除2个项(因为您两次调用stack2.pop() ),然后得到一个ArrayOutOfBounds异常。您应该用x替换第二个代码,并将所有stack2.op()代码借方替换为x。
发布于 2014-10-20 15:43:37
您应该这样做:只执行一次stack2.pop()并检查。超出绑定异常是因为您执行的pop操作比stack大小要多。
for(int i=0; i<21;i++)
{
int x=stack2.pop();
if(x==0%3)
stack.push(x);
else
stack.push(x);
if(x == 1%3)
stack4.push(x);
else
stack.push(x);
if(x == 2%3)
stack3.push(x);
else
stack.push(x);https://stackoverflow.com/questions/26469343
复制相似问题