类型的空指针内的成员访问,C编程是回文的



我正试图使用非递归解决方案解决LeetCode上的isPalindome((问题,当我使用VSCode运行此代码时,它会运行并给我正确的输出,但当我在LeetCode编译器中运行它时,它给我下面提到的错误。

你能帮我解决这个问题吗?对我的代码有什么修改可以帮助我以更好的方式解决问题吗?

bool isPalindrome(struct ListNode* head){
struct ListNode * NewHead, *MidList, *EndList;
NewHead = EndList = MidList = head;
struct ListNode *ptr_SecondHalf, *ptr_FirstHalf;
while (EndList->next  != NULL)
{
EndList = EndList->next->next;

MidList = MidList->next;
if (EndList->next == NULL || EndList->next->next  == NULL){
//ODD
if (EndList->next == NULL){
ptr_SecondHalf = MidList->next;
break;
}
//EVEN
if (EndList->next->next  == NULL){
ptr_SecondHalf = MidList->next;
break;
} 
}

}

MidList->next = NULL;
ptr_FirstHalf = head;
// Reverse SecondHalf
struct ListNode* ptr_SecondHalf_Reversed = NULL;
struct ListNode* current = ptr_SecondHalf;
struct ListNode* next = NULL;

while (current != NULL) {
// Store next
next = current->next;

// Reverse current node's pointer
current->next = ptr_SecondHalf_Reversed;

// Move pointers one position ahead.
ptr_SecondHalf_Reversed = current;
current = next;
}

while (ptr_FirstHalf->next != NULL && ptr_SecondHalf_Reversed != NULL){

if (ptr_FirstHalf->val == ptr_SecondHalf_Reversed->val){
if (ptr_FirstHalf->next->next != NULL || ptr_SecondHalf_Reversed ->next != NULL){
ptr_FirstHalf = ptr_FirstHalf->next;
ptr_SecondHalf_Reversed = ptr_SecondHalf_Reversed ->next ;
}
else
{
break;
}

}else{
printf("false n");
return false;
}
}
printf("true n");
return true;
}

第12行:Char 21:运行时错误:类型为"structListNode"[solution.c]的空指针内的成员访问

你的解决方案想法没有错,但太难实现,也没有任何错误,我建议我的解决方案,或者建议写一个方法,它会返回反向列表,然后比较这两个。

bool isPalindromeRec(struct ListNode* left, struct ListNode* right) {
if(right == NULL) return true;
if(isPalindromeRec(left, right->next) && left->val == right->val) {
left = left->next;
return true;
}
return false;
}
bool isPalindrome(struct ListNode* head){
if(head == NULL) return true;
struct ListNode * left = head;
struct ListNode * right = head;
bool ans = isPalindromeRec(left, right);
// happy now Vlad from Moscow?
if(ans) printf("truen");
else printf("falsen"); 
return ans;
}

我刚刚提出的这个解决方案应该是正确的——它只是从左到右比较每个节点,但我认为现在不是改变很多的时候。编辑:

bool isPalindrome(struct ListNode *head) {

if(head == NULL|| head->next== NULL)
return true;

//find list center
struct ListNode *fast = head;
struct ListNode *slow = head;

while(fast->next != NULL && fast->next->next != NULL){
fast = fast->next->next;
slow = slow->next;
}

struct ListNode *secondHead = slow->next;
slow->next = NULL;

//reverse second part of the list
struct ListNode *p1 = secondHead;
struct ListNode *p2 = p1->next;

while(p1 != NULL && p2 != NULL){
struct ListNode *temp = p2->next;
p2->next = p1;
p1 = p2;
p2 = temp;
}

secondHead->next = NULL;

//compare two sublists now
struct ListNode *p = (p2 == NULL?p1:p2);
struct ListNode *q = head;
while(p!=NULL){
if(p->val != q->val)
return false;

p = p->next;
q = q->next;

}

return true;
}

相关内容

  • 没有找到相关文章

最新更新