Search code examples
javastackqueuepalindrome

Determine Palindrome by Comparing Stack and Queue


So for my assignment I have to write a program that uses instances of StackArrayBased.java and QueueArrayBased.java and sends a string to both of them and compares the dequeue() and pop() method returns to determine if the string is a palindrome. I have written the program but it is not returning the correct boolean, please help.

public class IsPalindrome{
    public static void main(String[]args){
        String str = new String("abcba");
        String str2 = new String("abcde");
        System.out.println(isPal(str));
        System.out.println(isPal(str2));
    }
    public static boolean isPal(String str)
    {
        StackArrayBased stack = new StackArrayBased();
        QueueArrayBased queue = new QueueArrayBased();

        String s = new String();
        for (int i = 0; i < str.length( ); i++) {
            s = "" + str.charAt(i);
            System.out.println(s);
            queue.enqueue(s);
            stack.push(s);
        }
        // start to compare
        while (!queue.isEmpty( )) {
            if (queue.dequeue( ) != stack.pop( ))
                return false;
        }
        // finished w/ empty queue (and empty stack)
        return true;
    }
}

Solution

  • You're adding strings to the queue and stack and you should generally avoid using the standard equality checks for strings (since they compare object identity rather than content).

    Change:

    if (queue.dequeue( ) != stack.pop( ))
    

    to:

    if (!queue.dequeue().equals(stack.pop()))
    

    For example, this code (modified somewhat) works correctly:

    import java.util.LinkedList;
    import java.util.Queue;
    import java.util.Stack;
    
    public class Test   {
        public static void main(String[]args){
            String str = new String("abcba");
            String str2 = new String("abcde");
            System.out.println(isPal(str));
            System.out.println(isPal(str2));
        }
        public static boolean isPal(String str)
        {
            Stack<String> stack = new Stack<String>();
            Queue<String> queue = new LinkedList<String>();
    
            String s = new String();
            for (int i = 0; i < str.length( ); i++) {
                s = "" + str.charAt(i);
                System.out.println(s);
                queue.add(s);
                stack.push(s);
            }
            // start to compare
            while (!queue.isEmpty( )) {
                if (!queue.remove().equals(stack.pop( )))
                    return false;
            }
            // finished w/ empty queue (and empty stack)
            return true;
        }
    }
    

    outputting:

    a
    b
    c
    b
    a
    true
    a
    b
    c
    d
    e
    false