练习—单链表—Swap Nodes in Pairs

时间:2022-01-01 17:02:18

Given a linked list, swap every two adjacent nodes and return its head.

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

改变指针:

if (!head || !(head->next) )    return head;
ListNode *cur = head,*next = head->next;
head = head->next;
while(next){
    next = next->next;//next->3
    cur->next->next =cur;//2->1
    if(!next || !(next->next)) {
      cur->next = next;//1->3;
      return head;  }
    cur->next = next->next;//否则 1->4
    cur = next;// cur ->3
    next = next->next;//next->4
}
return head;

只改变值:

ListNode* swapPairs(ListNode* head)
{
    if(!head) return nullptr;
    ListNode *frontPtr=head,*backPtr=head->next;
    while(frontPtr && backPtr){     swap(frontPtr->val,backPtr->val);
        frontPtr=frontPtr->next;
        if(frontPtr!=nullptr)
            frontPtr=frontPtr->next;
        backPtr=backPtr->next;
        if(backPtr!=nullptr)
            backPtr=backPtr->next;
    }
    return head;
}

递归:

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if(head == NULL||head->next==NULL) return head;
        ListNode* next = head->next;
        head->next = swapPairs(next->next);
        next->next = head;
        return next;
    }
};