// Guide to Data Structures
// Section 2.7
// Copyright 2018, by J.T. Streib and T. Soma
import java.util.*;
public class PalindromeVersion2 {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
int i, j;
String word;
boolean isPalindrome;
StackArrayGeneric<Character> stack;
System.out.print("Enter a word: ");
word = scanner.next();
stack = new StackArrayGeneric<Character>(word.length()/2);
for(i=0; i<word.length()/2; i++)
stack.push(word.charAt(i));
j = i;
if(word.length()%2 != 0)
j++;
isPalindrome = true;
while(!stack.empty() && isPalindrome) {
if(stack.pop() != word.charAt(j))
isPalindrome = false;
j++;
}
if(isPalindrome)
System.out.println("The word you entered is a palindrome.");
else
System.out.println("The word you entered is NOT a palindrome.");
}
}
public class StackArrayGeneric<T> {
private static final int N = 3;
private int top;
private T[] sarray;
// constructors
public StackArrayGeneric() {
this(N);
}
public StackArrayGeneric(int n) {
top = 0;
sarray = (T[]) new Object[n];
}
// value returning methods
public boolean empty() {
return top <= 0;
}
private boolean full() {
return top >= sarray.length;
}
public T pop() {
T item = null;
if(empty())
throw new RuntimeException("Stack is empty");
top--;
item = sarray[top];
return item;
}
// void method
public void push(T item) {
if(full())
throw new RuntimeException("Stack is full");
sarray[top]=item;
top++;
}
}