Exercise 4 - Checking A Palindrome Using Stacks
Exercise 4 - Checking A Palindrome Using Stacks
Exercise number : 4
Date: 5th August, 2021
• Algorithm :
Step 1 : Start the program
Step 2 : Include libraries <iostream> and <conio.h>
Step 3 : Define maximum value for a variable MAX as 50
Step 4 : Define a structure stack
Step 5 : Inside function main traverse step 6 to step 14
Step 6 : Declare stack s; string string_1, string_2 = ""; char character;
int i
Step 7 : Call function s.init()
Step 8 : Input string_1 as a user-defined string
Step 9 : For i < 0; i < string_1.length(); i++ repeat step 10
Step 10 : Call function s.push() - Parameter : string_1[i]
Step 11 : Do execute step 12 to step 14 while character != '\0'
Step 12 : Set character = Call function s.pop() - Parameter : None
Step 13 : Execute step 14 if character != '\0'
Step 14 : Set string_2 = string_2 + character
Step 15 : Execute step 16 if string_1 == string_2 else execute step 17
Step 16 : Display string_1 as a palindrome
Step 17 : Display string_1 as not a palindrome
Register number : URK20DA1009
Name : Judah Felix
20CA2013 Data Structures Lab
Step 18 : Call function getch()
Step 19 : Return 0
Step 20 : End the program
‣ Structure stack :
Step 1 : Declare char a[MAX], top
Step 2 : Define a method - init(); Parameters : None;
Return type : void
Step 3 : Define a method - isFull(); Parameters : None;
Return type : int
Step 4 : Define a method - isEmpty(); Parameters : None,
Return type : int
Step 5 : Define a method - pop(); Parameters : None;
Return type : char
Step 6 : Define a method - push(); Parameters : char data;
Return type : int
Step 7 : End the structure
» Method init() :
Step 1 : Set top = 0
Step 2 : End the method
» Method isFull() :
Step 1 : Execute step 2 if top == MAX – 1 else execute step 3
Step 2 : Return 1
Step 3 : Return 0
Step 4 : End the method
» Method pop() :
Step 1 : Execute step 2 if not isEmpty() else execute step 3
Step 2 : Return a[--top]
Step 3 : Return '\0'
Step 4 : End the method
struct stack
{
char a[MAX], top;
void init()
{
top = 0;
}
int isFull()
{
if (top == MAX - 1)
return 1;
else
return 0;
}
int isEmpty()
{
if (top == 0)
return 1;
else
return 0;
}
char pop()
{
if (!isEmpty())
return a[--top];
else
return '\0';
}
void push(char data)
{
if (!isFull())
a[top++] = data;
else
cout << "The stack is full!";
}
};
cout << "Enter a string : ";
cin >> string_1;
for (i = 0; i < string_1.length(); i++)
s.push(string_1[i]);
do
{
character = s.pop();
if (character != '\0')
string_2 = string_2 + character;
} while (character != '\0');
if (string_1 == string_2)
cout << "\n" << string_1 << " is a palindrome!";
else
cout << "\n" << string_1 << " is not a palindrome!";
getch();
return 0;
}
• Output 1 :
Register number : URK20DA1009
Name : Judah Felix
20CA2013 Data Structures Lab
noon is a palindrome!
• Output 2 :
Enter a string : Moon
• Result :
The above program was executed and the output was verified
for a sample set of input values.