Is there any better C++ answer ?


  • 2
    S
    /************************
     * author : s2003zy
     * weibo  : weibo.com/songzy982
     * blog   : s2003zy.com
     ************************/
    class Solution {
    public:
        void swapNode(ListNode* pre, ListNode *first, ListNode* second) {
            pre -> next = second;
            first -> next = second -> next;
            second -> next = first;
        }
        ListNode *swapPairs(ListNode *head) {
            ListNode preHead(0);
            preHead.next = head;
            ListNode * pre = &preHead;
            while (pre && pre ->next && pre -> next -> next) {
                swapNode(pre, pre -> next, pre -> next -> next);
                pre = pre -> next -> next;
            }
            return preHead.next;
        }
    };

  • 0
    C
    //Humblebrag...
    
    class Solution {
    public:
        ListNode* swapPairs(ListNode* head) {
            if (head == NULL || head->next == NULL) return head;
            ListNode *grandChild = swapPairs(head->next->next);
            ListNode *child = head->next;
            child->next = head;
            head->next = grandChild;
            return child;
        }
    };

  • 0
    S

    In C 0 ms solution
    struct ListNode* swapPairs(struct ListNode* head) {

    struct ListNode* dummy=head;
    struct ListNode* prev=NULL;
    struct ListNode* Nextnode=NULL;
    if(!dummy)
      return head;
    
    while(dummy!=NULL && dummy->next!=NULL){
    
        Nextnode=dummy->next;
        dummy->next=Nextnode->next;
    
        if(prev)
          prev->next=Nextnode;
        else
          head=Nextnode;
    
        Nextnode->next=dummy;
    
        prev=dummy;
    
        dummy=dummy->next;
    
    
    
    
    
    }
    
    return head;
    

    }


Log in to reply
 

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