gpt4 book ai didi

java - Java 中的堆栈推送、弹出、查看算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:39:06 24 4
gpt4 key购买 nike

我了解堆栈的工作原理,但我必须编写 push、pop 和 peek 方法,然后在驱动程序类中实现它们。这就是令人困惑的地方。这是我的 Stack 类:

public class Stack implements StackInterface
{
private final int ARRAY_SIZE = 9;
private String[] movies = new String[ARRAY_SIZE]; // Hold movie titles
private int top = 0;

/**
* Constructor
* @param moviesIn
*/

public Stack(String[] moviesIn)
{
movies = moviesIn;
}

/**
* Test for full stack
*/

public void push(String moviesIn)
{
if (top >= movies.length)
System.out.println("ERROR: Stack is full");

top++;
movies[top] = moviesIn;
}

/**
* Test for empty stack
*/

public String pop()
{
if (top == 0) {
System.out.println("ERROR: Stack is empty");
return " ";
}

top--;
return movies[top];
}

public void peek()
{
// ???
}
}

到目前为止,这是我的 main() 方法中的内容:

public static void main(String[] args) 
{
String[] movies = {"Amour", "*Argo", "Beasts of the Southern Wild", "Django Unchained", "Les Misérables", "Life of Pi", "Lincoln", "Silver Linings Playbook", "Zero Dark Thirty"};
Stack oscarStack = new Stack(movies);

oscarStack.push(movies);
}

我以为我可以只将一个对象传递到堆栈,但它似乎不是那样工作的。那么如何将 oscarStack 对象压入堆栈呢?还是我必须单独插入每个字符串?在继续我的在线研究时,堆栈构造函数似乎只能创建一个空堆栈。这就是我不能传递对象参数的原因吗?

最佳答案

在 main 中,您将所有元素隐式放置到后备数组中,而无需任何推送操作。您可能想要做的是遍历要推送的电影,然后将它们推送进来。

应该做两个改变:

  • 将 Stack 对象更改为不再接受字符串数组。这是令人困惑和不必要的,因为所有初始化都是在构建时完成的。
  • 您的推送 有两个错误:
    • 您没有考虑数组为空的情况。切换顶部增量,或使用 movies[top++]
    • 如果数组已满,您实际上不会阻止代码执行。如果您尝试使用现有的运行,您将得到 ArrayIndexOutOfBoundsException


public static void main(String[] args)  {
String[] movies = {"Amour", "*Argo", "Beasts of the Southern Wild", "Django Unchained", "Les Misérables", "Life of Pi", "Lincoln", "Silver Linings Playbook", "Zero Dark Thirty"};
Stack oscarStack = new Stack();

for(String movie : movies) {
oscarStack.push(movie);
}
}

关于java - Java 中的堆栈推送、弹出、查看算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15390790/

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