A Straight-forward 4ms C++ Solution


  • 0
    Y
    class Solution {
    public:
        ListNode* swapPairs(ListNode* head) {
            ListNode newHead(0);
            newHead.next = head;
            ListNode *pre = &newHead, *cur = head, *next, *temp = NULL;
            while(cur && cur->next) {
                next = cur->next;
                temp = next->next;
                pre->next = next;
    	    cur->next = temp;
    	    next->next = cur;
    	    pre = cur;
    	    cur = cur->next;
            }
            
            return newHead.next;
        }
    };
    

Log in to reply
 

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