A solution in the C language


  • 0
    M
    
    /**
    
     * Definition for singly-linked list.
    
     * struct ListNode {
    
     *     int val;
    
     *     struct ListNode *next;
    
     * };
    
     */
    
        struct ListNode* swapPairs(struct ListNode* head) {
    
        struct ListNode* pre=(struct ListNode*)malloc(sizeof(struct ListNode));
    
    	struct ListNode* p=(struct ListNode*)malloc(sizeof(struct ListNode));
    
    	struct ListNode* temp=(struct ListNode*)malloc(sizeof(struct ListNode));
    
    	int i=0;
    
    	pre=head;
    
    	if(head==NULL||head->next==NULL)
    
    		return head;
    
        p=pre->next;
    
        head=p;
    
        while(p!=NULL&&p->next!=NULL&&p->next->next!=NULL)
    
    	{
    
    		temp=p->next;
    
    		pre->next=p->next->next;
    
    		p->next=pre;
    
    		p=temp->next;
    
    		pre=temp;
    
    	}
    
        if(p->next==NULL)
    
        {
    
            pre->next=NULL;
    
            p->next=pre;
    
            return head;
    
        }
    
        if(p->next->next==NULL)
    
        {
    
            pre->next=p->next;
    
            p->next=pre;
    
        }
    
        return head;
    
    }
    

Log in to reply
 

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