My AC C++ code, with easy idea


  • 0
    J
    class Solution {
    public:
    	ListNode *swapPairs(ListNode *head) {
            if(!head)
                return NULL;
            if(head->next == NULL)
                return head;
            ListNode* ret = new ListNode(0), *prev = ret, *cur = head;
    		ret->next = cur;
    		head = head->next;
            while(head)
            {
    			prev->next = head;
    			cur->next = head->next;
    			head->next = cur;
    			prev = cur;
    			cur = cur->next;
    			if(!cur)
    				break;
    			head = cur->next;
            }
    		return ret->next;
        }
    };
    

    using a extra node ret as prev


Log in to reply
 

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