【问题标题】:How is it possible to find the highest value in a stack? (java)如何找到堆栈中的最大值? (爪哇)
【发布时间】:2021-08-05 23:25:14
【问题描述】:

我正在准备堆栈考试,并且正在练习有关堆栈的各种方法。我试图实现一个返回堆栈中最大值的方法,但我有点困惑。

我应该移除this 的栈顶并将其推入新的栈s1,然后将this.stackTops1.stackTop 进行比较。

这是我的代码:

        Stack s1 = new Stack();
        
        if(this.isEmpty()) {
            System.out.println("the stack is empty ");
            return NOT_FOUND;
        }
        
        while(!this.isEmpty() && this.stackTop() > s1.stackTop()) {
            s1.push(this.stackTop());
            this.pop(); 
        }
        
        while(!s1.isEmpty()) {
            this.push(s1.stackTop());
            s1.pop();
        }
    }

我只是很困惑,不知道如何继续,所以任何帮助将不胜感激。

【问题讨论】:

  • 您的逻辑已关闭。我们需要第二个堆栈来“记录”第一个堆栈中的内容,因此必须弹出第一个堆栈的每个元素,然后将其推送到第二个堆栈。这样做时,我们可以在单个 int 变量中“记录”最大值(假设 Stack 是 int`s 的 Stack)。第一次迭代后,我们需要将第二个堆栈中的所有元素添加回第一个堆栈,以恢复我们之前的状态。
  • 你为什么要比较this.stackTop() > s1.stackTop()。没有意义。您应该不断弹出堆栈直到它变空,并将最大值存储在一个变量中。
  • 逻辑与在数组中查找最大元素相同。
  • @SauravKumar 考虑我从初始堆栈中弹出所有元素(1 x 1)并将它们推入另一个堆栈s1,我应该如何比较这些元素?
  • 回答您的问题,在弹出时,您必须将元素与当前最大的元素(将存储在变量中)进行比较。最初,最大的元素是 MIN_INT。

标签: java linked-list stack


【解决方案1】:

如果堆栈未排序(通常不会排序,因为对堆栈进行排序会非常低效),您需要遍历整个堆栈。因此,您必须遍历每个元素,直到堆栈为空,就像从数组中查找最大数一样。在堆栈上虽然您无法访问堆栈中间的元素,但您必须使用s1 来跟踪和“转移”主堆栈中的元素,以便能够比较它们。找到最大值后,您需要将 s1 中的所有元素返回到主堆栈。

想象你有一个盒子。在这个盒子里有书,大小都一样,完全适合盒子。这意味着您不能只从盒子中取出任何书。因此,要找到页数最多的书,您需要取出每本书并将其与您找到的当前最大的书进行比较。既然你想把书按顺序放回去,你就把它们放在第二个盒子里。之后,当你找到最长的一本书时,将每本书从临时盒子里拿出来放回原来的盒子里。

// Create your temporary stack
Stack s1 = new Stack();
// Initialize the first value with the minimal value
int largest = Integer.MIN_VALUE;

if (this.isEmpty()) {
    System.out.println("the stack is empty ");
    return NOT_FOUND;
}

// Loop through the main stack until it's empty
while (!this.isEmpty()) {
    // Take out the top element
    int current = this.pop();
    // Compare it to the largest that you have found until now
    if (current > largest) {
        // If it's larger remember it
        largest = current;
    }

    // And put it into the temporary stack
    s1.push(current);
}

// Loop through the temporary stack until it's empty
while (!s1.isEmpty()) {
    // Take the top element from the temporary stack and put it onto the main one
    this.push(s1.pop());
}

【讨论】:

  • 你不应该用勺子喂食。他需要帮助来理解而不是完成作业。
  • 是的,我没听懂发生了什么,但感谢您的帮助。
猜你喜欢
  • 2011-11-24
  • 2013-04-06
  • 1970-01-01
  • 2014-12-24
  • 1970-01-01
  • 2021-05-02
  • 2016-05-17
  • 2011-03-03
  • 2013-09-17
相关资源
最近更新 更多