You are required to write a program in JAVA based on the problem description given. Read the problem description and write a complete program with necessary useful comment for good documentation. Compile and execute the program. ASSIGNMENT OBJECTIVES: • To introduce queue data structure. DESCRIPTIONS OF PROBLEM:
Exercise : Write a 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
Program :
import java.util.Stack;
import java.util.Queue;
import java.util.*;
import java.util.Scanner;
class Main
{
// create an empty stack and Queue of characters
static Stack<Character> stack = new Stack<Character>();
static Stack<Character> stack1 = new Stack<Character>();
static Queue<Character> q = new LinkedList<Character>();
public static String Result(String str)
{
// push every character of the given string into the stack
char[] ch = str.toCharArray();
int k = 0;
for (int i = 0; i < str.length(); i++)
stack.push(ch[i]);
// pop characters from the stack until it is empty to Queue
while (!stack.isEmpty())
{
q.add(stack.pop());
}
// push characters from the Queue until it is empty to stack
while (!q.isEmpty())
{
stack1.push(q.remove());
}
while (!stack1.isEmpty())
{
// assign each popped character back to the character array
ch[k++] = stack1.pop();
}
// convert the character array into string and return it
return String.copyValueOf(ch);
}
public static void main (String[] args)
{
Scanner o = new Scanner(System.in); // Create a Scanner object
System.out.print("Enter String:");
String str = o.nextLine(); // Read user input
System.out.println("Result :" +Result(str)); //Call Result method and print output.
}
}
Output :
Thank You Have a Great Day !!! Please do like.
Get Answers For Free
Most questions answered within 1 hours.