先给出正确代码:
class Solution {
//定义迭代函数,用于翻转一段链表
private:
void reverse(ListNode*head)
{
ListNode* cur=head;
ListNode* pre=nullptr;
while(cur!=nullptr){
ListNode* nex=cur->next;
cur->next=pre;
pre=cur;
cur=nex;
}
}
public:
ListNode* reverseKGroup(ListNode* head, int k) {
//加个虚假节点便于对整个链表操作
ListNode* dummy=new ListNode(0,head);
ListNode* pre=dummy;
ListNode* RightNode;
while(RightNode!=nullptr){
ListNode* LeftNode=pre->next;
RightNode=pre;
//判断剩下长度是否小于k
for(int i=0;i<k;++i)
{
RightNode=RightNode->next;
if (RightNode==nullptr)
{return dummy->next;}
}
//准备下一段要翻转的链表的头
ListNode* nex=RightNode->next;
//断开要翻转的链表
pre->next=nullptr;
RightNode->next=nullptr;
reverse(LeftNode);
//接回原来的链表,并找到下一段要翻转的pre
pre->next=RightNode;
LeftNode->next=nex;
pre=LeftNode;
}
return head;
}
};
在写代码的过程中出现了引用空指针问题
runtime error: member access within null pointer of type 'ListNode' (solution.cpp) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:50:29
检查发现for循环那几行代码出现了问题,我刚开始写成了,
ListNode* LeftNode=pre->next;
RightNode=LeftNode;
for(int i=0;i<k-1;++i)
{
RightNode=RightNode->next;
if (RightNode==nullptr)
{return dummy->next;}
}
当输入的k值为1 的时候,如果像上面这么写会跳过for循环,对RightNode==nullptr这一步无法判断。所以在ListNode* nex=RightNode->next;的时候会引用空指针。