C++ 4ms code AC


  • -2
    Z
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* swapPairs(ListNode* head) {
            if(head == NULL || head->next == NULL) return head;
            ListNode*p = head,*q = NULL,*m = NULL,*n = NULL,*newhead = NULL;
            while(1)
            {
                q = p->next;
                if(q == NULL)
                break;
                if(newhead == NULL)
                newhead = q;
                m = q->next;
                q->next = p;
                p->next = NULL;
                if(m == NULL)
                break;
                n = m->next;
                p->next = n?n:m;
                p = m;
                q = n;
            }
            return newhead;
            
            
        }
    };

Log in to reply
 

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