What is wrong with my code, why empty result


  • 0
    X

    /**

    • Definition for singly-linked list.

    • public class ListNode {

    • int val;
      
    • ListNode next;
      
    • ListNode(int x) {
      
    •     val = x;
      
    •     next = null;
      
    • }
      
    • }
      */
      public class Solution {
      public ListNode swapPairs(ListNode head) {
      if (head == null || head.next== null){
      return head;
      }
      // cur and fast is
      ListNode cur = head;
      ListNode fast = head;

       while (cur!= null){
           // fast is the element on the second position originally
          
           // store the node for next cycle
           
           // fast point to previous
           
           fast = cur.next;
           
           if (fast != null){
               ListNode temp = cur.next.next;
               fast.next = cur;
               
               if (temp != null){
                   if (temp.next != null){
                       cur.next = temp.next;
                   }else{
                       cur.next = temp;
                       temp.next = null;
                   }
               }else{
                   cur.next = null;
                   break;
               }
               cur = temp;
           }else{
               cur.next = null;
               break;
           }
      
        }
        return head.next;
        
    }
    

    }

    this is my code. Test {1,2} shows that result is {}. I have searched. But did not find out any clues why it is wrong


  • 1
    M

    before function:

    head
      1   ->   2   ->   null
    

    after function:

              head
      2    ->  1   -> null
    

    return head.next returns null.

    At the start, you need to record "head.next" and return that at the end instead of returning "head.next" after you've reversed it.


Log in to reply
 

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