settingsAccountsettings
Menusettings

Q: Reverse Numbers with a Stack - Java Task (Stacks)

+13 votes

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:

Input

Output

1 2 3 4 5

5 4 3 2 1

1

1

 

asked in Java category by user golearnweb
edited by user golearnweb

1 Answer

+1 vote
 
Best answer

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/

answered by user samfred5830
selected by user golearnweb
...