My solution in C++,4ms


  • 0
    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;
    		ListNode *hn = head->next;
    		ListNode *q = hn;
    		ListNode *t;
              /***devide the list into two lists:head&hn and then merge hn&head into a single list hn;***/
    		while (p->next)
    		{
    			p->next = q->next;
    			p = q;
    			t = q->next;
    			if(t)
    			{
    			    q->next = t->next;
    			    q = t;
    			}
    		}
    		return mergeList(hn,head);
    	}
    	ListNode* mergeList(ListNode *l1,ListNode *l2)
    	{
    		ListNode* p = l1;
    		ListNode* q = l2;
    		ListNode* p1;
    		ListNode* q1;
    		while (p->next && q->next)
    		{
    			p1 = p->next;
    			q1 = q->next;
    			q->next = p->next;
    			p->next = q;
    			p = p1;
    			q = q1;
    		}
    		if(q)
    			p->next = q;
    		return l1;
    	}
    };

Log in to reply
 

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