Simple C++ solution


  • 1
    P
    class Solution {
    public:
        ListNode* swapPairs(ListNode* head) {
            if(head)
        	{
        		ListNode * prevNode = NULL;
        		ListNode * tmp = NULL;
        		ListNode  * curr = head;
        
        		while(curr && curr->next)
        		{
        			tmp = curr->next;
        			curr->next = tmp->next;
        			tmp->next = curr;
        
        			if(prevNode)
        				prevNode->next = tmp;
        			else
        				head = tmp;
        
        			prevNode = curr;
        			curr = curr->next;
        		}
        
        		return head;
        	}
        	else
        		return head;
            }
    };

Log in to reply
 

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