【问题标题】:Throwing elements of a node list on stack将节点列表的元素扔到堆栈上
【发布时间】:2013-06-12 02:44:11
【问题描述】:

我正在使用 Java,并且我有一个节点列表,我需要在 Stack 上按从最后到第一个的顺序使用 List。

例子:

我的列表是 {node1,node2,node3}

我的堆栈应该是

{

节点1,

节点2,

节点3

}

如何轻松解决这个问题?

这行得通吗?

if (hasWhiteNeighbor(startNode)) {
        List<Node> conNodes = getAdjacentNodes(startNode);
        while (conNodes.size() > 0) {
            int conCount = conNodes.size();
            stack.push(conNodes.get(conCount));
            conNodes.remove(conCount);
        }
    }

【问题讨论】:

标签: java list stack


【解决方案1】:

由于 List 保证迭代的顺序与添加元素的顺序相同,您可以轻松解决这个问题,只需按正确的顺序将节点添加到列表中,然后遍历列表并添加每个元素到堆栈。

List<String> stringList = new ArrayList<String>();
stringList.add("node1");
stringList.add("node2");
stringList.add("node3");

Deque<String> stringStack = new ArrayDeque<String>();
for (String s : stringList) {
  stringStack.push(s);
}

while (!stringStack.isEmpty()) {
  System.out.println(stringStack.pop());
}

上面的代码产生这个输出:

node3
node2
node1

链接
http://docs.oracle.com/javase/7/docs/api/java/util/List.html
http://docs.oracle.com/javase/7/docs/api/java/util/Stack.html
http://docs.oracle.com/javase/7/docs/api/java/util/Deque.html

【讨论】:

  • 您应该建议不建议将堆栈用于 LIFO。 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
猜你喜欢
  • 2015-07-04
  • 2018-09-20
  • 2017-03-27
  • 2016-11-26
  • 2012-04-26
  • 1970-01-01
  • 1970-01-01
  • 2010-10-28
  • 2019-02-05
相关资源
最近更新 更多