方法:n1、n2两两交换但是由于两两交换之后n1与接下来的n3、n4仍有联系否则交换后n1的next为n3而n4的next也为n3,导致n4丢失,所以我们在链表中的表头添加一个节点,使得两两交换的时候是三个有关节点进行交换,其中第一个节点位置不动后两个交换

    1. /**
    2. * Definition for singly-linked list.
    3. * struct ListNode {
    4. * int val;
    5. * ListNode *next;
    6. * ListNode() : val(0), next(nullptr) {}
    7. * ListNode(int x) : val(x), next(nullptr) {}
    8. * ListNode(int x, ListNode *next) : val(x), next(next) {}
    9. * };
    10. */
    11. class Solution {
    12. public:
    13. ListNode* swapPairs(ListNode* head) {
    14. if(!head||!head->next){
    15. return head;
    16. }
    17. ListNode d(0);
    18. d.next=head;
    19. head=&d;
    20. while(head&&head->next&&head->next->next){
    21. ListNode* n1=NULL;
    22. ListNode* n2=NULL;
    23. n1=head->next;
    24. n2=n1->next;
    25. n1->next=n2->next;
    26. n2->next=n1;
    27. head->next=n2;
    28. head=n1;
    29. }
    30. return d.next;
    31. }
    32. };