What is wrong with this code


  • 0
    S

    /**

    • 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) {
      struct ListNode *ptr=head,*temp1,*temp2;
      if(head==NULL || head->next==NULL)
      return head;

           while(ptr->next!=NULL && ptr!=NULL)
           {
               temp1=ptr->next;
               temp2=temp1->next;
               temp1->next=ptr;
               ptr->next=temp2;
               if(ptr)
               ptr=ptr->next;
           }
       
           return head;
       }
      

      };
      I am getting a run time error


  • 0
    M

    Change your while to while(ptr!=NULL && ptr->next!=NULL).

    You're accessing a variable in a null object.


Log in to reply
 

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