In: Computer Science
2. Using the Stack ADT:
In Java please.
import java.io.*;
import java.util.*;
public class Main
{
//method to insert an element on the top of the stack
static void push(Stack<Character> st, char element)
{
st.push(element);
}
//method to get an elemet from the top of the stack
static char pop(Stack<Character> st)
{
char p;
p = st.pop();
return p;
}
public static void main (String[] args)
{
Stack<Character> st = new Stack<Character>();
Scanner sc = new Scanner(System.in);
Scanner input = new Scanner(System.in);
//get the number of lines
System.out.print("Enter the number of lines: ");
int num = sc.nextInt();
//get the input string lines
for(int i=0; i<num; i++)
{
String str = input.nextLine();
for(int k=0; k<str.length(); k++)
{
char c = str.charAt(k);
push(st, c);
}
push(st, '\n');
}
//display the result
System.out.print("\nThe reverse strings are: ");
while(!st.isEmpty())
{
System.out.print(pop(st));
}
}
}
OUTPUT:
Enter the number of lines: 2
hello hi yes you can do it
ok bye
The reverse strings are:
eyb ko
ti od nac uoy sey ih olleh