3
06/11/2024 7:42 am
Topic starter
Write a program that reads N integers from the console and reverses them using a stack.
Use the Stack<Integer> class. Just put the input numbers in the stack and pop them.
Examples:
1 Answer
2
06/11/2024 7:43 am
Here is the solution (read the comments in the code to understand it better):
import java.util.*; public class Pr_01_ReverseNumbersWithStack { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String[] input = sc.nextLine().split(" ");//GETTING THE NUMBERS Stack<Integer> stack = new Stack<>(); for (int i = 0; i < input.length; i++) { stack.push(Integer.parseInt(input[i]));//PUSHING THEM INTO THE STACK } Collections.reverse(stack);//SINCE STACK IS A SUBCLASS OF COLLECTIONS, WE CAN USE COLLECTIONS' REVERSE METHOD TO REVERSE THE NUMBERS for (Integer integer : stack) { System.out.print(integer + " ");//PRINTING THE REVERSE ORDER OF THE NUMBERS } } }
The main thing here is to understand that Stacks are subclass of Collections, so you can use Collections' method reverse to reverse the order of the numbers (Integers) in the code;
Read more about the Collections here: https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html and another example here (for the ArrayList): http://beginnersbook.com/2013/12/sort-arraylist-in-descending-order-in-java/