简体   繁体   English

我们如何编写一个函数List multiPop(int k)来从堆栈中弹出k个元素,或者直到堆栈为空?

[英]How can we write a function List multiPop(int k) that pops k elements from the stack or until the stack is empty?

I am trying to write a method that pops k elements from the stack. 我正在尝试编写一种从堆栈中弹出k个元素的方法。 Any help would be appreciated. 任何帮助,将不胜感激。

This is what I have tried: 
    public void multipop(int k) { 
    List l = nil(); 
    while (true) {
    for(int i =0; i < k; i++) { 
    }

Translate the following concept in to Java: 将以下概念转换为Java:

create a list to store the popped members in.
while (the stack is not empty and we have to pop more elements) {
    add a popped member from the stack to the list
}
return the list.

Done 完成

list multipop(int k, list stack){

   int increment = 0;
   while(stack.next() != null && k < increment){ 
      stack.pop();
      increment++;
   }
}
return stack;

I'm sorting assuming you have the methods .next() and .pop() already created. 我在假设您已经创建了.next()和.pop()方法的情况下进行排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM