文章目录
Leetcode24 两两交换链表
链接: https://leetcode.cn/problems/swap-nodes-in-pairs/description/
思路: 明确交换规律. 由于中间节点交换时需要插入到两个节点中间, 所以为了保持统一, 引入一个虚拟的头结点. 那么交换规律为:
0 -> 1 -> 2 -> 3 -> 4
^ ^ ^
last cur next
1->3: cur->next = next->next;
2->1: next->next = cur;
0->2: last->next = next
此时的交换结果为:
0 -> 2 -> 1 -> 3 -> 4
^ ^ ^
last next cur
在下次循环前, 需更新索引
last = cur;
cur = cur->next;
ListNode* swapPairs(ListNode* head) {
if (head == nullptr || head->next == nullptr) {
return head;
}
ListNode* dummy_head = new ListNode(0);
dummy_head->next = head;
ListNode* current_node = head;
ListNode* last_node = dummy_head;
while (current_node!= nullptr && current_node->next != nullptr) {
ListNode* next_node = current_node->next;
current_node->next = current_node->next->next;
next_node->next = current_node;
last_node->next = next_node;
// 更新索引
last_node = current_node;
current_node = current_node->next;
}
return dummy_head->next;
}