今天在做力扣题的时候遇到了一个错误

上网看了好多,都没有解决。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
ListNode *p=head;
int count=0;
ListNode *head1=new ListNode();
ListNode *q=head1;
ListNode *head2=new ListNode();
ListNode *w=head2;
if (p==nullptr)
{
return head;
}
while (p!=nullptr)
{
count++;
if (count%2==1)
{
q->next=p;
p=p->next;
q=q->next;
}else{
w->next=p;
w=w->next;
p=p->next;
}
}
//w->next=nullptr;
q->next=head2->next;
return head1->next;
}
};
最后终于找到了原因,就是因为w指针最后没有指向nullptr
加上注释的一行之后,问题解决!
1093

被折叠的 条评论
为什么被折叠?



