In: Computer Science
Queues, Deques and Priority Queues. Enter the necessary code where indicated (using: MyQues.java - below and questions) How would you use a stack to verify whether a given string is a palindrome or not? How would you check if a string is a palindrome or not, using queues and deques?
Q:- How would you use a stack to verify whether a given
string is a palindrome or not?
Java Code:--
import java.util.Stack;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
System.out.print("Enter any string:");
Scanner in=new Scanner(System.in);
String inputString = in.nextLine();
Stack stack = new Stack();
for (int i = 0; i < inputString.length(); i++) {
stack.push(inputString.charAt(i));
}
String reverseString = "";
while (!stack.isEmpty()) {
reverseString = reverseString+stack.pop();
}
if (inputString.equals(reverseString))
System.out.println("The input String is a palindrome.");
else
System.out.println("The input String is not a palindrome.");
}
}
Q:- How would you check if a string is a palindrome or not,
using queues and deques?
Java Code:-
import java.util.Queue;
import java.util.Scanner;
import java.util.LinkedList;
class Main {
public static void main(String[] args) {
System.out.print("Enter any string:");
Scanner in=new Scanner(System.in);
String inputString = in.nextLine();
Queue queue = new LinkedList();
for (int i = inputString.length()-1; i >=0; i--) {
queue.add(inputString.charAt(i));
}
String reverseString = "";
while (!queue.isEmpty()) {
reverseString = reverseString+queue.remove();
}
if (inputString.equals(reverseString))
System.out.println("The input String is a palindrome.");
else
System.out.println("The input String is not a palindrome.");
}
}