两两交换链表节点,为什么不能用head
这是我通过的代码,但是我之前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
这是为什么?
/**
* 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) 可以使用head/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */
func swapPairs(head *ListNode) *ListNode {
if head == nil || head.Next == nil{ return head }
dummy:=&ListNode{Next:head}
prev:=dummy
for head!=nil && head.Next!=nil{
// 把第二个结点摘取出来
next:=head.Next
// 先让第一个结点Next指向第三个结点
head.Next=next.Next
// 然后第二个结点和第三个结点断开关系
next.Next=head
// prev 指向临时结点
prev.Next=next
// 结点交换
prev = head
head=head.Next }
return dummy.Next} 本帖最后由 hdydy 于 2023-8-3 10:29 编辑
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* _HEAD = new ListNode(0, head);// 虚拟头节点
ListNode* p = _HEAD, *q = nullptr;// p->head->q,交换head和q之后,p后移2步
while(head && head->next) {
q = head->next;
head->next = q->next;
q->next = head;
p->next = q;
p = head;
head = p->next;
}
return _HEAD->next;
}
}; 太深奥了!!!
页:
[1]