Python Program to Check String is Palindrome using Stack


When it is required to check if a string is a palindrome using stack data structure, a stack class is created, and push and pop methods are defined to add and delete values from stack. Another method checks to see if the stack is empty or not.

Below is a demonstration for the same −

Example

 Live Demo

class Stack_structure:
   def __init__(self):
      self.items = []

   def check_empty(self):
      return self.items == []

   def push_val(self, data):
      self.items.append(data)

   def pop_val(self):
      return self.items.pop()

my_instance = Stack_structure()
text_input = input('Enter the string... ')

for character in text_input:
   my_instance.push_val(character)

reversed_text = ''
while not my_instance.check_empty():
   reversed_text = reversed_text + my_instance.pop_val()

if text_input == reversed_text:
   print("The string is a palindrome")
else:
print("The string isn't a palindrome")

Output

Enter the string... MalayalaM
The string is a palindrome

Explanation

  • A class named ‘Stack_structure’ is defined with ‘init’ method.

  • This method initializes an empty list.

  • Another method named ‘check_empty’ is defined that checks if the stack is empty or not.

  • Another method named ‘push_val’ is defined that adds elements to the stack.

  • Another method named ‘pop_val’ is defined that deletes elements from the stack.

  • An instance of this ‘Stack_structure’ is defined.

  • The string is taken from the user.

  • It is iterated over, and the ‘check_empty’ method is called on it.

  • Another empty string is defined, and the string is reversed.

  • This reversed string is stored in the empty string.

  • This reversed string and the string from the user are compared.

  • If they are same, it means it is a palindrome.

  • Otherwise, it is not a palindrome.

  • The relevant output is displayed on the console.

Updated on: 14-Apr-2021

733 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements