我应该如何弹出堆栈中的最后一个添加的项目,而是第一个添加的项目?我尝试了这个,但不起作用。谢谢你
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class Exercise0204 {
public static void main(String[] args) {
Stack<String> stack = new Stack<String>();
stack.push("bottom");
System.out.println(stack);
stack.push("second");
System.out.println(stack);
stack.push("third");
System.out.println(stack);
stack.push("fourth");
System.out.println(stack);
List list = new ArrayList(stack);
for (int i = 0; i <stack.size(); i++) {
list.remove(i);
}
}
}
谢谢。
如果您遇到了真正的堆栈,则可以将所有内容弹出并立即将其推入另一个堆栈。这将为您提供相反顺序的所有内容。然后,新堆栈的顶部元素将是原始底部元素。
public E bottomElement(Stack<E> stack) {
if (stack.isEmpty()) throw new IllegalArgumentException("empty stack");
// Flip the stack over.
final Stack<E> upsideDownStack = new Stack<E>();
do {
upsideDownStack.push(stack.pop());
} while (!stack.isEmpty());
final E result = upsideDownStack.peek();
// Flip the stack back over.
do {
stack.push(upsideDownStack.pop());
} while (!upsideDownStack.isEmpty());
return result;
}
如果要从堆栈中删除底部元素,而不仅仅是将其返回并将其保存在堆栈中,只需将upsideDownStack.peek()
更改为upsideDownStack.pop()
,然后更改最终的do
-while
循环到while
循环。
堆栈数据结构不能定义弹出第一个元素的行为。如前所述,这是LIFO数据结构。内部实施详细信息与此处无关(是链接列表还是引擎盖下的其他内容)。
我宁愿使用双端队列的java.util.deque。
Deque<String> deque = new LinkedList<>();
deque.push("S1");
deque.push("S2");
deque.push("S3");
deque.push("S4");
deque.push("S5");
deque.push("S6");
deque.push("S7");
deque.push("S8");
String last = deque.pollLast();
String first = deque.pollFirst();
不应该使用的是,堆栈在LIFO原理上起作用,这意味着最后一次出现的内容。您可能要寻找的是一个适用于FIFO原理的队列