【问题标题】:How do i push an item back into a stack that i just popped without creating an infinite loop?如何在不创建无限循环的情况下将项目推回刚刚弹出的堆栈?
【发布时间】:2022-11-22 02:01:58
【问题描述】:

我正在尝试使用以下逻辑为 Java 游戏创建一个循环:

if (the stack is not empty) {
 pop top move from stack.
 reset the board.
}

// then i create a while loop to pop the moves back onto the board.

while(stack is not empty) {
   type userMove = history.pop();
   assign userMove back onto the board.
}

我坚持的最后一点也是将我正在分配的用户移动推回到堆栈中。

如果我这样做:

while(stack is not empty) {
 type userMove = history.pop();
 assign userMove back onto the board. 
 history.push(userMove);
}

然后我将创建一个无限循环。所以我不确定如何做最后一步将这些动作推回到堆栈中。

【问题讨论】:

    标签: java loops stack


    【解决方案1】:

    堆栈不适合这里。 您可以使用双端队列或双端队列。

    top = deque.removeFromLast();
    
    while(deque.peek() != top) {
     type userMove = deque.removeFromLast();
     assign userMove back onto the board. 
     deque.addToFront(userMove);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-23
      • 1970-01-01
      • 1970-01-01
      • 2011-09-01
      • 2015-09-30
      • 2023-03-05
      • 1970-01-01
      • 2015-03-08
      相关资源
      最近更新 更多