这是我通过的代码,但是我之前18是
while(head != nullptr && (head->next) != nullptr)
然后报了错误:
Line 21: Char 35: runtime error: member access within null pointer of type 'ListNode' (solution.cpp)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:30:35
这是为什么?
[C++] 纯文本查看 复制代码 /**
* 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* swapPairs(ListNode* head) {
ListNode* _HEAD = new ListNode(0);//虚拟头节点
ListNode* fast = nullptr,*last = nullptr;
_HEAD->next = head;
last = _HEAD;
while(last->next != nullptr && (last->next->next) != nullptr)
{
fast = last->next;
ListNode* tmp = fast->next;
last->next = tmp;
fast->next = tmp->next;
tmp->next = fast;
last = last->next->next;
}
return _HEAD->next;
}
}; while(head != nullptr && (head->next) != nullptr)
|