C++ 链表是否回文
我对链表是新手,我试图解决这个问题,根据给定的链表是否为回文,我们必须返回true或false 给定指向第一个节点的指针C++ 链表是否回文,c++,linked-list,palindrome,C++,Linked List,Palindrome,我对链表是新手,我试图解决这个问题,根据给定的链表是否为回文,我们必须返回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; //Sp
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)
在这里,我首先将链表拆分为两个相等的部分,然后反转第二部分,然后逐个比较两个元素。
有人能帮你调试一下吗。你这里有个打字错误:
Node *temp2 = head, // , instead of ;
Node *temp1 = head;
注意,
而不是代码>
你需要:
Node *temp2 = head;
Node *temp1 = head;
或
是的,谢谢您为示例案例工作,但在我尝试提交时给出了分段错误。这是一个单独的问题。您需要自己提出一些导致segfault的测试用例。请显示一个显示输入列表的<代码>temp2=temp2->next->next代码>--您确定头部保证至少有3个节点吗?
Node *temp2 = head, *temp1 = head;