力扣刷题 24.两两交换链表中的节点--day4
题目分析
还是那句话, 需要先模拟一下节点交换的过程
将整个过程细分为一个个小过程,以此类推下去
注意画图分析设置三个指针 post cur pre
注意 1. 节点的交换过程 2. 指针的递推
解法
ListNode *swapPairs(ListNode *head)
{
if (!head)
return nullptr;
ListNode *dummyHead = new ListNode();
dummyHead->next = head;
ListNode *post = dummyHead, *cur = head, *pre = head->next;
while (cur && pre)
{
ListNode *temp = pre->next;
pre->next = cur;
cur->next = temp;
post->next = pre;
post = cur;
cur = cur->next;
if (cur == nullptr)
{
pre = nullptr;
}
else
{
pre = cur->next;
}
}
head = dummyHead->next;
delete dummyHead;
return head;
}
标签:24,pre,head,dummyHead,ListNode,cur,next,链表,节点
From: https://www.cnblogs.com/jianchuxin/p/17347943.html