What's wrong with my codes?


  • 0
    A

    Submission Result: Wrong Answer

    Input: {1,2}
    Output: {1}
    Expected: {2,1}

    class Solution {
    public:
        ListNode *swapPairs(ListNode *head) {
            if(head==NULL||head->next==NULL)
                return head;
            ListNode *pNode=head;
            ListNode *pNext=NULL;
            ListNode *pNextNext=NULL;
            while(pNode&&pNode->next)
            {
                pNext=pNode->next;
                
                if(pNext->next!=NULL)
                {
                    pNextNext=pNext->next;
                    pNext->next=pNode;
                    pNode->next=pNextNext;
                    
                    pNode=pNextNext;
                }
                else
                {
                    pNext->next=pNode;
                    pNode->next=NULL;
                }
            }
            return head;
        }
    };

  • 0
    M

    Head never changes what it looks at, so at the start, it's pointing at node 1, and at the end it's pointing at node 1. Since you then return it, your function causes the nodes to swap, then returns the final element in the new list, since that's where node 1 ends up. I suggest either recording the second element at the start, adding a blank node for the head to follow at start and returning blank->next at the end, or updating head when you swap nodes involving the head pointer.


Log in to reply
 

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