Next Greater Element(Code)

package NextGreaterElement;

public class Main {

    public static void main(String[] args) {

        int[] arr = {2, 1, 3, 8, 6, 7, 5};

        Stack<Integer> stack = new Stack<>(); //generic function
        for (int i = 0; i < arr.length; i++) {
            while (!stack.isEmpty() && arr[i] > stack.peek()) {
                int rv = stack.pop();
                System.out.println(rv + "->" + arr[i]);
            }
            stack.push(arr[i]);

        }


        while (!stack.isEmpty()) {
            int rv = stack.pop();
            System.out.println(rv + "->" + "-1");
        }
    }
}

Hi @SanjeevKumarRay,
Corrected your solution and the corrected solution is here -


Corrections are commented

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.