当前位置: 代码迷 >> 综合 >> LeetCode | Swap Nodes in Pairs
  详细解决方案

LeetCode | Swap Nodes in Pairs

热度:9   发布时间:2023-12-22 05:45:08.0

https://leetcode.com/problems/swap-nodes-in-pairs/

链表的操作题,往往画个图,逻辑就很清晰了。

C++

class Solution { public:ListNode* swapPairs(ListNode* head) {if (!head || !head->next) return head;ListNode dummy(0); dummy.next = head;ListNode *pre1 = &dummy, *ptr1 = head, *ptr2 = head->next;while (ptr1 && ptr2) {ptr1->next = ptr1->next->next;ptr2->next = ptr1;pre1->next = ptr2;pre1 = ptr1;ptr1 = pre1->next;if (ptr1) ptr2 = ptr1->next;else ptr2 = NULL;}return dummy.next;} };

转载于:https://www.cnblogs.com/ilovezyg/p/6375870.html

  相关解决方案