Java Program To Check Palindrome Using Stack
- June 19, 2020
- by
In this Java Program, we check palindrome using stack.
A word, phrase, number or sequence of words that reads same backward as forward are known as palindromes.
E.g. madam, civic, level, refer, 121 1331 etc.
The linear data structure which follows a particular order in which the operations are performed is known as a stack. The order may be LIFO (Last In First Out) or FILO (First In Last Out).
E.g. Plates stacked over one another in a canteen.
Logic : 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();
}
Step 1 : Import java.util.Stack
Step 2 : Import java.util.Scanner
Step 3 : Ask the user to enter any string by using Scanner
Step 4 : Create variable inputString and store the user's entered string in it.
Step 5 : Create constructor of stack
Step 6 : Apply for loop
Step 7 : Apply while loop
Step 8 : Display the result using System.out.print
Program :
import java.util.Stack;
import java.util.Scanner;
public class PalindromeStack
{
public static void main(String[] args)
{
System.out.print("Enter any string:");
Scanner sc = new Scanner(System.in);
String inputString = sc.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");
}
}
Output :
Enter any String : level
The input string is a palindrome
For execution of the same do visit my YouTube Channel :


0 comments:
Post a Comment