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;} };