In: Computer Science
Using the Stack ADT:
In Java please.
The solution of the above code is provided below. If you like the solution don't forget to give a thumbs up.
Solution part a:
ReverseStackOfWords.java
import java.util.Stack;
import java.util.*;
public class ReverseStackOfWords {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Stack<String> words = new Stack<>();
// storing few lines of text into text variable of string type
String text = sc.nextLine();
// splitting and storing into array of string type
String[] stringArray = text.split(" ");
// pushing string words into stack
for (String str : stringArray) {
words.push(str);
}
// using pop operation to remove and print the same elements using using poll()
// printing the elements in reverse order
System.out.println("Entered Text in Reverse order \n");
while(words.empty() != true) {
System.out.print(words.pop()+" ");
}
}
}
Output part 1:
Solution part b:
ReverseStackOfCharacters.java
import java.util.Scanner;
import java.util.Stack;
public class ReverseStackOfCharacters {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Stack<Character> charStack = new Stack<>();
// storing few lines of text into text variable of string type
String text = sc.nextLine();
// splitting and storing into array of string type
Character[] charArray = new Character[text.length()];
for(int c=0; c<text.length(); c++) {
charArray[c] = text.charAt(c);
}
// pushing string words into stack
for (Character ch : charArray) {
charStack.push(ch);
}
// using pop operation to remove and print the same elements using using poll()
// printing the elements in reverse order
System.out.println("Entered Text in Reverse order \n");
while(charStack.empty() != true) {
System.out.print(charStack.pop());
}
}
}
Output part b:
End of solution