java - 接受两个输入并分割队列的方法

标签 java methods data-structures queue

我想调用此方法将队列中的一部分元素发送到队列后面,但是当我在 main 中调用它时,它只显示一个空队列。 有没有更好的方法来做到这一点。

//m: the number of customers initially in line
//n: the portion of m that will be sent to the back of the queue today
public T lastCustomer(int m, int n)
{
int count;
ListNode<T> processed = new ListNode<T>(front.data);
while(rear!=null) 
{ 
  for(count=0;count< n;count++) 
{ 
  T extracted = dequeue(); 
      boolean check = enqueue(extracted); 
 if(check == true) continue; 
else break; 
}

processed.data = dequeue();
m--;
n=m/2; 
}


return processed.data;

}

最佳答案

队列为空的原因是

while(rear!=null)

结合:

processed.data = dequeue();

只要您的后方null并且队列为空,您就可以出队。 对于您的任务,您实际上不需要m:

public T lastCustomer(int n){
    T result = null;
    while(n > 0){ 
        result = dequeue(); 
        enqueue(result);//you probably don't need to check the result(depends on your implementation)
        n--;
    }
    return result
}

这应该可以完成工作

编辑:忘记n--;

编辑:合理化变量

关于java - 接受两个输入并分割队列的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33458292/

相关文章:

java - 添加方法java

Java:静态初始化 block 中的方法比主方法中的方法慢

c - 不理解在 C 中使用递归反转链表的代码片段

java - 想要获取最后一个元素的前一个对象。但返回空

java - 我的 Google map fragment 显示灰色。我无法显示实际 map

java - 处理 Cron 作业

java - 如何对带有String、String、String...作为参数的方法进行反射调用?

java - Spring 将一个 bean 的属性值注入(inject)另一个 bean

java - 使用非静态方法而不将其引用到对象?

java - 具有快速查找功能的排序集(与 HashSet 一样快?)