我是链表的新手,我试图解决这个问题,在这个问题中,我们必须根据给定的链表是否是回文返回true或false。
给定指向第一个节点的指针。
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;
}
我不能理解它给分割错误。 上面说:
Runtime Error:
Runtime ErrorSegmentation Fault (SIGSEGV)
在这里,我首先将链表分成相等的两半,然后反转后半部分,然后将元素一个一个地比较为2。 谁能帮忙调试一下。
这里有一个打字错误:
Node *temp2 = head, // , instead of ;
Node *temp1 = head;
请注意,
而不是;
。
你需要:
Node *temp2 = head;
Node *temp1 = head;
或
Node *temp2 = head, *temp1 = head;