无法使用堆栈集合以 LIFO 顺序读取
Not able to read in LIFO order using stack collection
我创建了一个双列表如下。
List<Stack<Vertex>> allPaths = new ArrayList<Stack<Vertex>>();
当我通过执行 DFS 收集堆栈中的所有路径并尝试使用 for each iterator over stack collection 打印每个堆栈时,它按 FIFO 顺序打印。
void print(List<Stack<Vertex>> allPaths){
for(Stack<Vertex> eachPath : allPaths){
for(Vertex eachVertex: eachPath){
System.out.print(eachVertex.name+" ");
}
System.out.println();
} // end of stack iterator
} // end of print() function
因此,如果每个节点访问完成的顺序是:4->3->2->1,它会打印 4->3->2->1。在这里使用什么而不是堆栈来获取后进先出顺序的最佳集合是什么?通过堆栈返回的迭代器的行为似乎有问题。它在 LIFO 中不起作用。
使用stack.pop
Stack<Integer> stack = new Stack<>();
stack.push(4);
stack.push(3);
stack.push(2);
stack.push(1);
while (!stack.empty()) {
System.out.println(stack.pop());
}
Stack
是 Java 1.0 的遗留 class,它扩展了 Vector
。 Vector
是 Java 1.0 的遗留 class,它是更新的 ArrayList
.
的同步版本
由于 Vector
由数组支持,将项目推入堆栈意味着 将 附加到数组(前置不会很好地执行)。弹出值意味着从数组中删除 last 值。作为堆栈,功能是正确的,但值以 FIFO 顺序物理存储在数组中。
如前所述,它们是遗留的 classes,您不应该使用它们,例如 Stack
的 javadoc 说:
A more complete and consistent set of LIFO stack operations is provided by the Deque
interface and its implementations, which should be used in preference to this class.
Deque
的 javadoc 说:
Deques can also be used as LIFO (Last-In-First-Out) stacks. This interface should be used in preference to the legacy Stack
class. When a deque is used as a stack, elements are pushed and popped from the beginning of the deque.
因此,迭代 Deque
将按 LIFO 顺序查看元素,而迭代 Stack
将按 FIFO 顺序查看元素。不过,两者都可以作为堆栈正常工作。
我创建了一个双列表如下。
List<Stack<Vertex>> allPaths = new ArrayList<Stack<Vertex>>();
当我通过执行 DFS 收集堆栈中的所有路径并尝试使用 for each iterator over stack collection 打印每个堆栈时,它按 FIFO 顺序打印。
void print(List<Stack<Vertex>> allPaths){
for(Stack<Vertex> eachPath : allPaths){
for(Vertex eachVertex: eachPath){
System.out.print(eachVertex.name+" ");
}
System.out.println();
} // end of stack iterator
} // end of print() function
因此,如果每个节点访问完成的顺序是:4->3->2->1,它会打印 4->3->2->1。在这里使用什么而不是堆栈来获取后进先出顺序的最佳集合是什么?通过堆栈返回的迭代器的行为似乎有问题。它在 LIFO 中不起作用。
使用stack.pop
Stack<Integer> stack = new Stack<>();
stack.push(4);
stack.push(3);
stack.push(2);
stack.push(1);
while (!stack.empty()) {
System.out.println(stack.pop());
}
Stack
是 Java 1.0 的遗留 class,它扩展了 Vector
。 Vector
是 Java 1.0 的遗留 class,它是更新的 ArrayList
.
由于 Vector
由数组支持,将项目推入堆栈意味着 将 附加到数组(前置不会很好地执行)。弹出值意味着从数组中删除 last 值。作为堆栈,功能是正确的,但值以 FIFO 顺序物理存储在数组中。
如前所述,它们是遗留的 classes,您不应该使用它们,例如 Stack
的 javadoc 说:
A more complete and consistent set of LIFO stack operations is provided by the
Deque
interface and its implementations, which should be used in preference to this class.
Deque
的 javadoc 说:
Deques can also be used as LIFO (Last-In-First-Out) stacks. This interface should be used in preference to the legacy
Stack
class. When a deque is used as a stack, elements are pushed and popped from the beginning of the deque.
因此,迭代 Deque
将按 LIFO 顺序查看元素,而迭代 Stack
将按 FIFO 顺序查看元素。不过,两者都可以作为堆栈正常工作。