In: Computer Science
Write a java program to reverse element of a stack. For any given word (from input), insert every character (from the word) into a stack. The output from the stack should be the same as the input. Your program should be using a stack and a queue to complete this process. 1. Push into stack 2. Pop from stack 3. Enqueue into queue 4. Dequeue from queue 5. Push into stack 6. Pop from stack and display java
Code
import java.util.*;
public class Main {
public static void main(String[] args) {
String word;
char c;
Scanner scnr=new
Scanner(System.in);
Stack<Character> stack=new
Stack<>();
Queue<Character> queue=new
LinkedList<>();
System.out.print("Enter word:
");
word=scnr.nextLine();
//push all the character from word
to Stack
for(int
i=0;i<word.length();i++)
stack.push(word.charAt(i));
//now one by one pop the character
and add that character to the queue
while(!stack.isEmpty())
{
c=stack.pop();
queue.add(c);
}
//now dequeue char from the queue
and add to the stack
while(!queue.isEmpty())
{
c=queue.poll();
stack.push(c);
}
//now pop char frommthe stack and
print
while(!stack.isEmpty())
{
c=stack.pop();
System.out.print(c);
}
System.out.println();
}
}
output
If you have any query regarding the code please ask me in the comment i am here for help you. Please do not direct thumbs down just ask if you have any query. And if you like my work then please appreciates with up vote. Thank You.