两两交换链表中的节点
    题目链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs/
    图片.png

    思路:三指针,考虑节点总数为奇数或偶数的情况。

    参考代码:

    1. class Solution {
    2. public:
    3. ListNode* swapPairs(ListNode* head) {
    4. if (!head || !head->next) {
    5. return head;
    6. }
    7. ListNode* pre = head;
    8. ListNode* curr = head->next;
    9. ListNode* temp = curr->next;
    10. head = curr;
    11. while (pre) {
    12. curr->next = pre;
    13. pre->next = temp;
    14. if (!pre->next || !pre->next->next) {
    15. break;
    16. }
    17. pre->next = pre->next->next;
    18. pre = temp;
    19. curr = pre->next;
    20. temp = curr->next;
    21. }
    22. return head;
    23. }
    24. };