链表两两交换节点:C++ 代码实现及优化
#include"ListNode.hpp"
class Solution { public: ListNode* swapPairs(ListNode* head) { if (head == nullptr || head->next == nullptr) { return head; } ListNode* newHead = head->next; ListNode* prev = nullptr; ListNode* curr = head;
while (curr != nullptr && curr->next != nullptr) {
ListNode* next = curr->next;
curr->next = next->next;
next->next = curr;
if (prev != nullptr) {
prev->next = next;
}
prev = curr;
curr = curr->next;
}
return newHead;
}
};
原文地址: http://www.cveoy.top/t/topic/poTt 著作权归作者所有。请勿转载和采集!