【刷题日记】链表-两两交换链表中的节点-L24-Medium
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
24. 两两交换链表中的节点
学习点
- 添加一个空的头节点,方便统一交换,不需要单独针对 head 节点设置
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| class Solution { public: ListNode* swapPairs(ListNode* head) { ListNode *head_node = new ListNode(-1, head); ListNode *pre = head_node; ListNode *curr = head;
while (curr != nullptr) { ListNode *post = curr->next; if (post != nullptr) { curr->next = post->next; post->next = curr; pre->next = post; } pre = curr; curr = curr->next; }
return head_node->next; } };
|