描述
在單鏈表中慎颗,兩兩交換臨近的節(jié)點鞋邑,返回鏈表的頭節(jié)點;
輸入:
1->2->3->4->nullptr
返回:
2->1->4->3->nullptr
分析
變量
dummy : next指針指向頭節(jié)點埂息;
cur :當前要操作的節(jié)點皮璧;
prev : 當前節(jié)點的前一個節(jié)點舟扎;
next : 當前節(jié)點的下一個節(jié)點;
運行條件
next不為空
運行邏輯
//指針指向的改變
prev->next = next;
cur->next = next->next;
next->next = cur;
// 更新指針
prev = cur;
cur = cur->next;
next = cur ? nullptr : cur->next;
實現(xiàn)
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;
}
更簡單的只交換節(jié)點值的實現(xiàn)
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;
}