Monday, June 2, 2014

Check if a character link list is palindrome or not.

Hi Folks,

Here is my implementation for checking whether link list is palindrome or not.

#include <iostream>
#include <stack>
#include <cstdlib>

struct node
{
int data;
struct node *next;
};

using namespace std;

struct node *head;

void addNode(int data)
{
struct node *temp;
temp = (struct node *) malloc(sizeof(struct node));
temp -> next = NULL;
temp->data = data;

if(head == NULL)
head = temp;
else
{
struct node *head1;
head1 = head;
while(head1 ->next != NULL)
{
head1 = head1->next;
}
head1->next = temp;
}
}


int main()
{
int N;
cin >> N;

for(int i=0;i<N;i++)
{
int temp;
cin >> temp;
addNode(temp);
}

struct node *slow, *fast;
stack<int> stk;

slow = head;
fast = head;

while(fast->next != NULL)
{
stk.push(slow->data);
slow = slow->next;
fast = fast->next;
if(fast->next != NULL)
fast = fast->next;
}

if(N %2 != 0)
slow = slow->next;
while(!stk.empty())
{

// cout << (stk.top()) <<" " << (slow->data) <<endl;
if(stk.top() == slow->data)
{
slow = slow->next;
stk.pop();
}
else
{
cout <<"No Pallindrome" <<endl;
return false;
}
}

cout <<"Pallindrome" <<endl;//return true;
}

No comments: