描述
在单链表中,两两交换临近的节点,返回链表的头节点;
输入:
1->2->3->4->nullptr
返回:
2->1->4->3->nullptr
分析
变量
dummy : next指针指向头节点;
cur :当前要操作的节点;
prev : 当前节点的前一个节点;
next : 当前节点的下一个节点;
运行条件
next不为空
运行逻辑
//指针指向的改变
prev->next = next;
cur->next = next->next;
next->next = cur;
// 更新指针
prev = cur;
cur = cur->next;
next = cur ? nullptr : cur->next;
实现
ListNode *swapNodeInPairs00(ListNode *head)
{
ListNode dummy(-1);
dummy.next = head;
ListNode *prev = &dummy;
ListNode *cur = prev->next;
ListNode *next = cur->next;
while (next) {
// 开始交换重组
prev->next = next;
cur->next = next->next;
next->next = cur;
prev = cur;
cur = cur->next;
next = cur ? cur->next : nullptr;
}
return dummy.next;
}
更简单的只交换节点值的实现
ListNode *swapNodeInPairs(ListNode *head)
{
ListNode *cur = head;
while (cur->next) {
int temp = cur->val;
cur->val = cur->next->val;
cur->next->val = temp;
cur = cur->next->next;
}
return head;
}