My C++ Solution


  • 0
    class Solution {
    public:
        ListNode* swapPairs(ListNode* head) {
            if (!head || !head->next) return head;
            ListNode* headNode = new ListNode(0);
    		headNode->next = head;
    		head = headNode;                    //insert head node;
    		ListNode* post = head->next;
    		ListNode* prev = head->next->next;
    		while (post && prev){
    			head->next = prev;
    			post->next = prev->next;
    			prev->next = post;
    			if (!post->next) break;
    			if (!post->next->next) break;
    			head = post;
    			prev = post->next->next;
    			post = post->next;
    		}
    		return headNode->next;
        }
    };

  • 0
    F
    This post is deleted!

Log in to reply
 

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