如何找到堆栈中的最高值? (java)

How is it possible to find the highest value in a stack? (java)

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

我应该移除 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();
        }
    }

我只是很困惑,不知道如何进行,因此我们将不胜感激。

如果堆栈未排序(通常情况下未排序,因为对堆栈进行排序效率非常低),您需要 运行 遍历整个堆栈。因此,您必须 运行 遍历每个元素,直到堆栈为空,就像从数组中查找最大数一样。尽管在堆栈上您无法访问堆栈中间的元素,因此您必须使用 s1 来跟踪和“移动”主堆栈中的元素以便能够比较它们。找到最大值后,您需要 return 将 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());
}