Share my 2s C soluton


  • 0
    S
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
     */
    struct ListNode *swapPairs(struct ListNode *head) {
        struct ListNode *p1,*p2,*p3;
        
        if(head && head->next)
        {
           p1 = head->next;
            
           while(p1->next && p1->next->next)
           {
              p2 = p1->next;
              p3 = p2->next;
              
              p1->next = p3;
              if(p3->next)
              {
                  p2->next = p3->next;
              }
              else
              {
                  p2->next = NULL;
              }
              
              p3->next = p2;
               
              p1 = p2;
           }
           
           p1 = head->next;
           head->next = p1->next;
           p1->next = head;
           
           return p1;
        }
    
    return head;
        
    }

Log in to reply
 

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