What's wrong with this code?


  • 0
    X

    class Solution {
    public:
    ListNode *swapPairs(ListNode *head) {
    ListNode *h1, *h2, *h3, *newhead, *h4;
    bool st = true;

    if (head->next->next == NULL){
    	newhead = head->next;
    	head->next = NULL;
    	newhead->next = head;
    	st = false;
    	return newhead->next;
    }
    
    if (head->next == NULL){
    	st = false;
    	return head;	
    }
    
    newhead=new ListNode;
    newhead->next = head;
    h2 = newhead;
    h4 = head;
    //showlist(newhead->next);
    
    while (st){
    	//cout << " Count " << endl;
    	//showlist(newhead->next);
    	if (h4->next == NULL){
    		//cout << "1" << endl;
    		st = false;
    		//showlist(newhead->next);
    		return newhead->next;
    	}
    
    	if (h4->next->next == NULL){
    		//cout << "2" << endl;
    		h1 = h2;
    		h2 = h1->next;
    		h3 = h2->next;
    		h1->next = h3;
    		h3->next = h2;
    		h2->next = NULL;
    		st = false;
    		//showlist(newhead->next);
    		return newhead->next;
    	}
    
    	if (h4->next->next != NULL){
    		//cout << "3" << endl;
    		h1 = h2;
    		h2 = h1->next;
    		h3 = h2->next;
    		h4 = h3->next;
    		h1->next = h3;
    		h3->next = h2;
    		h2->next = h4;
    	}
    }
    }
    

    };


Log in to reply
 

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