如何在Java中高效移除栈的底半部分元素?

huangapple go评论73阅读模式
英文:

How do I efficiently remove bottom half elements of a stack in Java?

问题

如何在Java中设计一种高效的方法来移除堆栈(stack)中下半部分的元素?例如:
我的堆栈是:(1,2,3,4,5,6)。输出应为4,5,6。另一个例子中,输入为(1,2,3,4,5,6,7,8,9,10,11)。输出将从6到11。

英文:

How can I devise an efficient method in Java to remove bottom half elements in a stack? For instance:
My stack is : (1,2,3,4,5,6). The output is 4,5,6. Another example where the input is ( 1,2,3,4,5,6,7,8,9,10,11). The output will be from 6 to 11.

答案1

得分: 1

如果您有堆栈中元素的计数,您可以将前半部分弹出,然后打印后半部分(如果您不想丢失元素,可以将其推入另一个堆栈)

如果堆栈中没有元素的计数,您需要创建另一个堆栈(称为堆栈2),从堆栈1中弹出元素并推入堆栈2,然后保持元素的计数。

一旦获得计数,从堆栈2中弹出元素并推入堆栈1,只打印从堆栈2中弹出的前半部分元素。

英文:

If you have count of elements in stack, you can just pop off first half and then print next half (push it to another stack if you dont want to lose your elements)

If you dont have count of elements in stack, you need to create another stack(say stack2), pop elements from stack1 and push to stack2 and then keep counts of elements.

Once you have got the count, pop elements from stack2 and push in stack1 and only print the first half elements being popped off from stack2.

答案2

得分: 1

可以这样做:

int center = stack1.size() / 2;
//移除一半
int counter = 0;
for(int i=0; counter<center; counter++) {
	stack1.remove(i);
}
英文:

You can do this:

int center = stack1.size() / 2;
//Remove the half
int counter = 0;
for(int i=0; counter&lt;center;counter++) {
	stack1.remove(i);
}

huangapple
  • 本文由 发表于 2020年8月23日 03:18:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/63540203.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定