Write a Java program using a combination of Stack and Queue to test to see if a
ID: 3802890 • Letter: W
Question
Write a Java program using a combination of Stack and Queue to test to see if a word is a palindrome. The program (algorithm) MUST BE NON-Recursive. prompt the user for an input word and store it in both a Queue and a Stack. Then pop a character at a time from the Stack and Queue and and match them. If they all match, then return TRUE else return FALSE. They must implement short circuiting i.e. if there is no match, immediately return FALSE.
must repeatedly run the program until the user enters "n " or "N" to stop the program.
Explanation / Answer
import java.util.ArrayList;
import java.util.Scanner;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Surya
*/
public class palindrome {
ArrayList<String> stack = new ArrayList<String>();//stack variable
ArrayList<String> queue = new ArrayList<String>();//queue variable
void push(String a)//method to push into stack
{
stack.add(a);
}
void popall()//emptying stack
{
while(stack.size()>0)
{
stack.remove(0);
}
}
void dequeueall()//emptying queue
{
while(queue.size()>0)
{
queue.remove(0);
}
}
String pop()//method to pop from stack
{
if(stack.size()>0)
{
String s=stack.get(stack.size()-1);
stack.remove(stack.size()-1);
return s;
}
return "";
}
void enqueue(String a)//method to add to queue
{
queue.add(a);//adding to queue
}
String dequeue()//method to remove from queue
{
if(queue.size()>0)
{
String s=queue.get(0);
queue.remove(0);
return s;
}
return "";
}
static boolean check_palindrome(palindrome p)
{
while(p.stack.size()>0)
{
String s= p.pop();//top element in stack
String r = p.dequeue();//frist element in queue
// System.out.println(s+" "+r);
if(!s.equals(r))
return false;
}
return true;
}
public static void main(String argv[])
{
String s;
//varaible declaraions..
Scanner sc= new Scanner(System.in);
int i;
char c;
palindrome p = new palindrome();
System.out.println("Enter word:");//prompting input
s= sc.next();//reading input;;
while(!(s.equals("N")||s.equals("n")))
{
for(i=0;i<s.length();i++)
{
c=s.charAt(i);
p.push(Character.toString(c));//adding to stack
p.enqueue(Character.toString(c));//adding to queue
}
//printing output
if(check_palindrome(p))
{
System.out.println("IS palindrome");
}
else
{
System.out.println("Not a palindrome");
}
p.popall();
p.dequeueall();
System.out.println("Enter word:(N or n to stop)");//prompting input
s= sc.next();//reading input;;
}
}
}
output:-
run:
Enter word:
amma
IS palindrome
Enter word:(N or n to stop)
nanna
Not a palindrome
Enter word:(N or n to stop)
tattat
IS palindrome
Enter word:(N or n to stop)
N
BUILD SUCCESSFUL (total time: 13 seconds)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.