Runtime Error in Swap Nodes in Pairs


  • 0
    V

    I keep getting a runtime error in the below code. Can someone tell me where I might be going wrong. Thank you.

      /**
         * 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 *current=head;
                ListNode *nextnode=current->next;
                head=nextnode;
                while(current!=NULL&&nextnode!=NULL){
                    current->next=nextnode->next;
                    nextnode->next=current;
                    current=current->next;
                    nextnode=current->next;
                }
                return head;
            }
        };

  • 1
    S
            while(current!=NULL&&nextnode!=NULL){
                current->next=nextnode->next;
                nextnode->next=current;
                current=current->next;
                nextnode=current->next;   // What if current is NULL ? 
            }

Log in to reply
 

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