What is wrong with this solution


  • 0
    G

    Could anybody explain what's wrong with this solution?

    public ListNode reverseKGroup(ListNode head, int k) {
        if (head==null||head.next==null||k<2) return head;
        
        ListNode tail = head;
        ListNode first = head;
        ListNode second = first.next;
        
        for (int i = 0; i < k - 1; i++) {
            tail = tail.next;
            if (tail == null)
                return head;
        }
        ListNode dummy = new ListNode(0);
        dummy.next = tail;
        head.next = tail.next;
        while (first.next != head.next) {
            ListNode temp = second.next;
            second.next = first;
            first = second;
            second = temp;
        }
        return dummy.next;
    }
    

    Input:[1,2]
    2
    Output:[2]
    Expected:[2,1]


Log in to reply
 

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