这道题又是套路的一个特殊情况,具体代码如下:
class Solution { public: ListNode* swapPairs(ListNode* head) { if (head == NULL || head->next == NULL) { return head; } ListNode* dummyHead = new ListNode(0); dummyHead->next = head; ListNode* prev = dummyHead; ListNode* cur = prev->next; ListNode* nex = cur->next; int len = 0; while(cur) { ++len; cur = cur->next; } while(len >= 2) { cur = prev->next; nex = cur->next; cur->next = nex->next; nex->next = prev->next; prev->next = nex; nex = cur->next; prev = cur; len -= 2; } ListNode* retHead = dummyHead->next; delete dummyHead; return retHead; } };
class Solution {public: ListNode* swapPairs(ListNode* head) { if (head == NULL || head->next == NULL) { return head; } ListNode* dummyHead = new ListNode(0); dummyHead->next = head; ListNode* prev = dummyHead; ListNode* cur = prev->next; ListNode* nex = cur->next; int len = 0; while(cur) { ++len; cur = cur->next; } while(len >= 2) { cur = prev->next; nex = cur->next; cur->next = nex->next; nex->next = prev->next; prev->next = nex; nex = cur->next; prev = cur; len -= 2; } ListNode* retHead = dummyHead->next; delete dummyHead; return retHead; }};