Write a Java program to Check if a queue is palindrome or not


The Java code checks whether the queue of characters is a palindrome or not. A palindrome is a sequence of characters that reads the same backward as forward.

The code uses two queues: the original queue and a reversed queue (created by copying the elements of the original queue). It then compares corresponding elements from both queues to determine if the original queue is a palindrome.

  • It creates a queue named queue using the LinkedList implementation of the Queue interface and adds the characters 'r', 'a', 'd', 'a', and 'r' to it.
  • It initializes a boolean variable isPalindrome to true, assuming that the queue is a palindrome initially.
  • It creates another queue named reverseQueue, which is a copy of the original queue.
  • The code then enters a loop that continues until the original queue is empty. In each iteration, it dequeues (removes) a character c1 from the original queue and dequeues a character c2 from the reverseQueue.
  • It compares c1 and c2 to check if they are different. If they are not equal, it means the corresponding characters in the original and reversed queues are not the same, indicating that the original queue is not a palindrome. In this case, the isPalindrome flag is set to false, and the loop is terminated using the break statement.
  • After the loop finishes, the code checks the value of isPalindrome. If it's true, it means the queue is a palindrome, and the corresponding message is printed. Otherwise, if isPalindrome is false, it means the queue is not a palindrome, and a different message is printed.

Source Code

import java.util.LinkedList;
import java.util.Queue;
 
public class QueuePalindrome
{
	public static void main(String[] args)
	{
		Queue<Character> queue = new LinkedList<>();
 
		// Adding elements to the queue
		queue.add('r');
		queue.add('a');
		queue.add('d');
		queue.add('a');
		queue.add('r');
 
		// Checking if the queue is palindrome
		boolean isPalindrome = true;
 
		Queue<Character> reverseQueue = new LinkedList<>(queue);
		while (!queue.isEmpty())
		{
			char c1 = queue.remove();
			char c2 = reverseQueue.remove();
			if (c1 != c2)
			{
				isPalindrome = false;
				break;
			}
		}
 
		if (isPalindrome)
		{
			System.out.println("The Queue is a Palindrome");
		}
		else
		{
			System.out.println("The Queue is not a Palindrome");
		}
	}
}
 

Output

The Queue is a Palindrome

Example Programs