Works under IDE, unacceptable here with runtime error.What's wrong?


  • 0
    T
    ListNode *swapPairs(ListNode *head) {
    	ListNode *p, *q;
    	p = head;
    	while (p->next != NULL){
    		q = p->next->next;
    		p->next->next = p;
    		if (p == head) head = p->next;
    		if (q == NULL){
    			p->next = NULL; break;
    		}
    		if (q->next == NULL) p->next = q;
    		else p->next = q->next;
    		p = q;
    	}
    	return head;
    }

  • 0
    T

    Solved.

    class Solution {
    public:
        ListNode *swapPairs(ListNode *head) {
        	if(head == NULL) return head;
        	ListNode *p, *q;
        	p = head;
        	while (p->next != NULL){
        		q = p->next->next;
        		p->next->next = p;
        		if (p == head) head = p->next;
        		if (q == NULL){
        			p->next = NULL; break;
        		}
        		if (q->next == NULL) p->next = q;
        		else p->next = q->next;
        		p = q;
        	}
        	return head;
        }
    };

Log in to reply
 

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