Given a singly linked list of size N of integers. The task is to check if the given linked list is palindrome or not.
Input: First line of input contains number of testcases T. For each testcase, first line of input contains length of linked list N and next line contains N integers as data of linked list.
Output: For each test case output will be 1 if the linked list is a palindrome else 0.
User Task: The task is to complete the function isPalindrome() which takes head as reference as the only parameter and returns true or false if linked list is palindrome or not respectively.
Constraints:
1 <= T <= 103
1 <= N <= 50
Example(To be used only for expected output):
Input:
2
3
1 2 1
4
1 2 3 4
Output:
1
0
Explanation: Testcase 1: 1 2 1, linked list is palindrome.
My Code:
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <stack>
using namespace std;
/* Link list Node */
struct Node {
int data;
struct Node *next;
Node(int x) {
data = x;
next = NULL;
}
};
void append(struct Node** head_ref, struct Node **tail_ref, int new_data)
{
struct Node* new_node = new Node(new_data);
if (*head_ref == NULL)
*head_ref = new_node;
else
(*tail_ref)->next = new_node;
*tail_ref = new_node;
}
bool isPalindrome(Node *head);
/* Driver program to test above function*/
int main()
{
int T,i,n,l;
cin>>T;
while(T--){
struct Node *head = NULL, *tail = NULL;
cin>>n;
for(i=1;i<=n;i++)
{
cin>>l;
append(&head, &tail, l);
}
cout<<isPalindrome(head)<<endl;
}
return 0;
}
}
/*This is a function problem.You only need to complete the function given below*/
/*
struct Node {
int data;
struct Node *next;
Node(int x) {
data = x;
next = NULL;
}
};
*/
/*You are required to complete this method */
bool isPalindrome(Node *head)
{
Node *front=head;
if(head==NULL)
{
return -1;
}
int len=0;
while(front!=NULL)
{
front=front->next;
len++;
}
front=head;
stack <int> s;
if(!(len%2))
{
int m=(len/2);
while(m-- && front)
{
s.push(front->data);
front=front->next;
}
int k=(len/2);
while(k-- && !s.empty())
{
int q= s.top();
s.pop();
if(q==front->data)
{
front=front->next;
continue;
}
else
{
break;
}
}
}
else
{
int m=(len/2)-1;
while(m-- && front)
{
s.push(front->data);
front=front->next;
}
front=front->next;
int k=(len/2)-1;
while(k-- && !s.empty())
{
int q= s.top();
s.pop();
if(q==front->data)
{
front=front->next;
continue;
}
else
{
break;
}
}
}
if(s.empty())
{
return 1;
}
else
{
return 0;
}
}
I'm getting Segmentation Fault-SIGSEGV.