【问题标题】:Stack to --> ArrayList Java堆栈到 --> ArrayList Java
【发布时间】:2015-04-03 12:49:45
【问题描述】:

我做了一个 Stack 和一个 ArrayList 来进行研究。实际上,我现在想让我的 Stack 替换为 ArrayList,但是如何将 Stack 转换为 ArrayList 呢? push、pop ... 的情况如何?

谢谢

public static ArrayList<State> search(State finalstate)
{
    ArrayList<State> toreturn = new ArrayList<State>();
    Stack<State>mystack=new Stack<State>();
    mystack.push(initState);
    State currState;
    currState=initState;
    while(!mystack.isEmpty() && !currState.equals(finalstate) )
    {
        currState=mystack.pop();
        toreturn.add(currState);
        if(currState.vecinos.containsKey("up"))
        {
            mystack.push(currState).vecinos.get("up");
        }
        if(currState.vecinos.containsKey("down"))
        {
            mystack.push(currState).vecinos.get("down");
        }
        if(currState.vecinos.containsKey("left"))
        {
            mystack.push(currState).vecinos.get("left");
        }
        if(currState.vecinos.containsKey("right"))
        {
            mystack.push(currState).vecinos.get("right");
        }
    }

    return toreturn;
}

【问题讨论】:

  • popStack 中删除项目,push 将项目添加到 Stack。为什么在复制到 List 时将项目添加到 Stack?当方法完成时,你想在你的List 中做什么?
  • 只是为了在List中留下痕迹
  • 只是为了跟踪*抱歉
  • 这是什么意思?您在复制 Stack 时正在修改它...这可能不是您想要的。

标签: java arraylist stack


【解决方案1】:

Stack是一个Collection,可以使用ArrayList(Collection)构造函数

list = new ArrayList(stack);

【讨论】:

  • 这是有问题的。如果我们按以下顺序将内容推入堆栈:1、2、3、4、5,那么令人惊讶的是,ArrayList 也会以 [1、2、3、4、5] 结束,而我们可能期望 [5、4、3 , 2, 1]
  • 是的,@Wei 是对的,这个方法导致堆栈的顺序相反。
【解决方案2】:

我发现将堆栈转换为列表的最简单方法是使用以下行:

List<Integer> stackToList = new ArrayList(stack);

但是,这会产生反转的堆栈。 这意味着,如果您的堆栈是 1, 2, 3 您会期望在列表 3, 2, 1 中,因为这是堆栈对象“弹出”的顺序。但事实并非如此,而是得到 1、2、3。所以,为了得到预期的输出,你需要执行

Collections.reverse (stackToList);

这将反转内联列表并为您提供3、2、1

【讨论】:

    【解决方案3】:

    上面的答案是不对的,因为顺序会颠倒。
    相反,您可以像这样迭代

    Stack<State> stack = new Stack<>();
    List<State> list = new ArrayList<>();
    while(!stack.isEmpty()) { 
        list.add(stack.pop()); 
    }
    

    【讨论】:

      【解决方案4】:

      改用双端队列,

      Deque<Integer> deque = new ArrayDeque<>();
      deque.push(1);
      deque.push(2);
      deque.push(3);
      System.out.println(new ArrayList<>(deque)); // 3, 2, 1
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-02-14
        • 2015-06-17
        • 1970-01-01
        • 2021-07-19
        • 1970-01-01
        • 2011-03-27
        • 2012-10-16
        相关资源
        最近更新 更多