My simple solution c++,4 ms


  • 0
    Y

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

    ListNode* second=head->next;
    head = second;
    while(first && second){
        ListNode* pre = first;
        first->next = second->next;
        second->next = first;
        first = first->next;
        if(!first) {first = nullptr;}
        else if(first->next) { second = first->next; pre->next = second;}  
                else {second = nullptr;}
    }
    return head;

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.