-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPalindrome(small_characters_only).cpp
102 lines (95 loc) · 1.75 KB
/
Palindrome(small_characters_only).cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include <iostream>
#include<cstring>
#define MAX 100
char str[MAX] ;
using namespace std;
//node structure
struct node{
char ch ;
node *next ;
};
//get memory for a new character
node * get_node(char ch){
node*newch = new node ;
newch->ch = ch ;
newch->next= NULL ;
return newch ;
}
void push(char ch, node**head){
if(*head==NULL){
*head = get_node(ch) ;
}
else{
node * newch = get_node(ch) ;
newch->next= *head;
*head = newch ;
}
}
char pop(node**head){
if(*head==NULL){
cout<<endl<<"Underflow";
return '!';
}
else{
char ch = (*head)->ch;
node * temp = *head;
*head =(*head)->next ;
free(temp); temp = NULL ;
return ch ;
}
}
void show(node * head){
while(head){
cout<<head->ch<<" ";
head = head->next ;
}
}
int list_size(node*head){
if(head==NULL){
return 0 ;
}
else{
return list_size(head->next)+1 ;
}
}
int palindrome(node*head){
if(head==NULL){
return 0 ;
}
else{
node*temp= NULL;
int s = list_size(head) ;
for(int i = 0 ; i <s/2;i++){
push(pop(&head),&temp);
}
//popped the middle character
//I think palindromes are odd +I tested some palindromes from a site so it's working fine
pop(&head);
while(head&&temp){
if(pop(&temp)!=pop(&head)){
return 0 ;
}
}
return (head==NULL)&&(temp==NULL);
}
}
//take a string from a user and push only important characters (from 'a' to 'z')
void take_str(node**head){
cout<<endl<<"Enter : ";
cin.get(str,100);
int i = 0 ;
while(*(str+i)!='\0'){
//Exclude any unnecessary characters and spaces
if(*(str+i)>='a'&&*(str+i)<='z'){
push(*(str+i),head);
}
i++;
}
}
int main()
{
node * head =NULL ;
take_str(&head);
cout<<endl<<palindrome(head);
return 0;
}