Reputation: 94
I'm new to Linked List and I was trying to solve this question where we have to return true or false on the basis of whether given linked List is palindrome or not.
Given a pointer to the 1st node.
bool isPalindrome(Node *head)
{
//Your code here
Node *startsecond = NULL;//will act as pointer to second Linked list
Node *temp2 = head;
Node *temp1 = head;
//Split LINKED LIST IN 2 PARTS
while(1){
temp2 = temp2->next->next;
if(temp2->next==NULL){//if linked list has odd no of elements
startsecond = temp1->next->next;
break;
}else{
startsecond = temp1->next;
break;
}
temp1 = temp1->next;
}
temp1->next=NULL;
//REVERSE THE SECOND LINKED LIST
Node *current = startsecond;
Node *prev = NULL, *next = NULL;
while(current!=NULL){
next = current->next;
current->next = prev;
prev=current;
current=next;
}
startsecond = prev;
while(head!=NULL && startsecond!=NULL){
if(startsecond->data == head->data){
head = head->next;
startsecond = startsecond->next;
}
else
return false;
}
return true;
}
I'm not able to understand it gives segmentation error. It says:
Runtime Error:
Runtime ErrorSegmentation Fault (SIGSEGV)
Here I'm first splitting the Linked List into 2 equal halves and then reverse the second half and then compare the elements to 2 one by one. Can someone please help debug.
Upvotes: 0
Views: 62
Reputation: 60218
You have a typo here:
Node *temp2 = head, // , instead of ;
Node *temp1 = head;
Notice the ,
instead of a ;
.
You need:
Node *temp2 = head;
Node *temp1 = head;
or
Node *temp2 = head, *temp1 = head;
Upvotes: 1