/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* VHead = new ListNode(0);
VHead->next = head;
ListNode* cur = VHead;
while (cur->next != NULL && cur->next->next != NULL) {
ListNode* temp = cur->next;
ListNode* temp1 = cur->next->next->next;
cur->next = cur->next->next;
cur->next->next = temp;
temp->next = temp1;
cur = cur->next->next;
}
return VHead->next;
}
};
时间复杂度:O(N)
空间复杂度:O(1)
思路:类似于对交换过程进行了模拟,因为用temp和temp1,所以很容易把过程模拟出来,只不过需要多一点空间。