1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 //这题对我来说很难 10 class Solution 11 { 12 public: 13 ListNode* swapPairs(ListNode* head) 14 { 15 ListNode* dummy = new ListNode(-1); 16 dummy -> next = head; 17 ListNode* cur = dummy; 18 19 while (cur != NULL) 20 { 21 ListNode* first = cur -> next; 22 if (first == NULL) break; 23 24 ListNode* second = first -> next; 25 if (second == NULL) break; 26 27 // 按照一定的次序,交换相邻的两个结点。 28 cur -> next = second; 29 first -> next = second -> next; 30 second -> next = first; 31 32 cur = first; 33 } 34 return dummy -> next; 35 } 36 };
原文:https://www.cnblogs.com/yuhong1103/p/12499234.html