3ab8350bf17c4cfcb454abe3be8041c4.png

【题目】:24. 两两交换链表中的节点

class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(head == nullptr || head->next == nullptr) {
return head;
}
ListNode* pre = new ListNode(0, head);
// c、a、b(她们仨的相对顺序)
ListNode *a = head, *b = head->next, *c = pre;
while(b) {
… b = temp->next;
}
return pre->next;
}
};
  • 时间复杂度: O(n)
  • 空间复杂度: O(1)

7da52351f9834381ab35dba8c9ba1fe4.png