Check Palindrome

Implement a function to check if a linked list is a palindrome.

C++:
01 bool isPalindrome(Node* head)
02 {
03     int cnt=0;
04     for(Node* tmp=head;tmp;tmp=tmp->next)
05         cnt++;
06     stack <int> s;
07     Node* tmp=head;
08     for(int i=0;i<cnt/2;i++){
09         s.push(tmp->value);
10         tmp=tmp->next;
11     }
12     if(cnt%2)
13         tmp=tmp->next;
14     for(int i=0;i<cnt/2;i++){
15         if(s.top()!=tmp->value)
16             return false;
17         s.pop();
18         tmp=tmp->next;
19     }
20     return true;
21 }
Advertisements
This entry was posted in Array and linked list, Stack and Queue. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s