gpt4 book ai didi

java - 迭代器是否违反堆栈/队列数据结构?

转载 作者:行者123 更新时间:2023-11-30 06:49:07 25 4
gpt4 key购买 nike

正如我们所知,Java 中每个实现 Collection 的类接口(interface)应实现Iterator<E> iterator()方法。

StackQueue是集合层次结构的一部分,也实现此方法。所以我们可以这样写:

Stack stack = new Stack();
// Deque stack = new ArrayDeque<>();
stack.add( "1" );
stack.add( "2" );
stack.add( "3" );

Iterator i = stack.iterator();
while ( i.hasNext() ) {
Object o = i.next();
if ( o.equals( "2" ) ) {
i.remove();
}
}

我的担忧是:

  1. 我们可以从堆栈/队列中间删除元素吗?

  2. 堆栈/队列应该只“显示”一个元素(堆栈中的最后一个元素和队列中的第一个元素),但实际上我们可以在不调用“pop”、“enqueue”方法的情况下获取所有这些元素吗?

最佳答案

从最严格的意义上讲,StackQueue 不应允许对其元素进行迭代,但此限制存在的唯一原因是证明这些数据结构的存在是合理的。根据sgi

Stack does not allow iteration through its elements.

This restriction is the only reason for stack to exist at all. Note that any Front Insertion Sequence or Back Insertion Sequence can be used as a stack; in the case of vector, for example, the stack operations are the member functions back, push_back, and pop_back. The only reason to use the container adaptor stack instead is to make it clear that you are performing only stack operations, and no other operations.

虽然某些实现遵循这一点,例如 C++ 中的 std::stack 不公开 iterator,但其他实现提供迭代器作为一项功能。 Stack java中的Vector构建于实现迭代器Vector之上。 Queue构建于Collection 之上,需要实现iterator。回答您的问题

Is it ok that we are able to delete elements from the middle of the stack/queue?

是的。底层实现将确保您的堆栈/队列在删除后处于一致的状态。

Is it ok that stack/queue should "show" only one element (last in stack and first in queue) but actually we are able to get all of them without calling "pop","enqueue" methods?

是的,这是底层实现的一个功能。

关于java - 迭代器是否违反堆栈/队列数据结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43363808/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com