Unable to identify error in the code


#1

The code goes into infinite loop for the given test case: 1->2->3->4
Output is like: 2->1->4->3->4->3->4->3-…

Can somebody help, here’s my code.

/**

  • Definition for singly-linked list.

  • struct ListNode {

  • int val;
    
  • ListNode *next;
    
  • ListNode(int x) : val(x), next(NULL) {}
    
  • };
    /
    ListNode
    Solution::swapPairs(ListNode* A) {
    if(A == NULL)
    return A;

    ListNode* curr = A;
    ListNode* ahead = curr->next;
    if(ahead == NULL)
    return A;

    ListNode* temp = A;
    int flag = 0;
    ListNode* head;
    ListNode* prev = NULL;
    while((temp!=NULL) && (temp->next))
    {
    ListNode* first = temp;
    ListNode* second = temp->next;
    ListNode* s_next = second->next;
    second->next = first;
    if(flag == 0)
    {
    head = second;
    flag = 1;
    }
    else
    {
    if(prev != NULL)
    prev->next = second;
    }
    prev = first;
    temp = s_next;
    }
    return head;
    }


#2

You didn’t make the next pointer of last element = NULL


#3

Thank you very much, that rectified the code.