Problem: 24. 两两交换链表中的节点
错误
while(dummyHead->next != nullptr && dummyHead->next->next != nullptr)
此处是cur
要记住,要交换后面两节点,必定得到两个节点的前面一个节点。
复杂度
$O(n)$
$O(1)$
Code
`
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| class Solution { public: ListNode* swapPairs(ListNode* head) { if (head == nullptr) return nullptr; ListNode* dummy = new ListNode(0),*pre = dummy,*cur = head; dummy->next = cur; while (cur != nullptr) { ListNode* next = cur->next; if(next == nullptr) break; ListNode* nextNext = next->next; pre->next = next; next->next = cur; cur->next = nextNext;
pre = cur; cur = nextNext; } return dummy->next; } };
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class Solution { public: ListNode* swapPairs(ListNode* head) { ListNode* dummyHead = new ListNode(0); dummyHead->next = head; ListNode* cur = dummyHead; while(cur->next != nullptr && cur->next->next != nullptr) { ListNode* tmp = cur->next; ListNode* tmp1 = cur->next->next->next;
cur->next = cur->next->next; cur->next->next = tmp; cur->next->next->next = tmp1;
cur = cur->next->next; } return dummyHead->next; } };
|