Help! I got different execution results form leetcode and my local pc..


  • 0
    U

    below is my code.

    var reverseKGroup = function(head, k) {
        if(!head || !head.next){
            return head;
        }
        var node = head.next;
        var stack = [];
        var hNode = head;
        while(node){
            // console.log(node.val+":"+hNode.val);
            stack.push(node);
            
            node = node.next;
            
            if(stack.length === k){
                while(stack.length > 0){
                    // console.log(hNode);
                    hNode.next = stack.pop();
                    hNode = hNode.next;
                    // console.log(stack.length);
                }
            }
        }
        
        for(var i=0;stack&&i<stack.length;i++){
            hNode.next = stack[i];
            hNode = hNode.next;
        }
        hNode.next = null;
        return head;
    };
    

    Submission Result is wrong, according to leetcode.
    input = [1, 2] 2
    output = [1, 2]
    expected = [2, 1]

    So, I test it on my local pc with the code below( reverseKGroup is the same):

    // leetcode
    function ListNode(val){
        this.val = val;
        this.next = null;
        this.chain = function(nextNode){
            this.next = nextNode;
            return nextNode;
        };
        this.print = function(){
            var node = this;
            var str = "";
            while(node){
                str += (node.val + " ");
                node = node.next;
            }
            console.log(str);
        }
    }
    
    var reverseKGroup = function(head, k) {
        if(!head || !head.next){
            return head;
        }
        var node = head.next;
        var stack = [];
        var hNode = head;
        while(node){
            // console.log(node.val+":"+hNode.val);
            stack.push(node);
            
            node = node.next;
            
            if(stack.length === k){
                while(stack.length > 0){
                    // console.log(hNode);
                    hNode.next = stack.pop();
                    hNode = hNode.next;
                    // console.log(stack.length);
                }
            }
        }
        
        for(var i=0;stack&&i<stack.length;i++){
            hNode.next = stack[i];
            hNode = hNode.next;
        }
        hNode.next = null;
        return head;
    };
    
    var head = new ListNode(null);
    head.chain(new ListNode(1)).chain(new ListNode(2));//.chain(new ListNode(3)).chain(new ListNode(4)).chain(new ListNode(5));
    var rs = reverseKGroup(head, 2);
    rs.print();
    
    

    and then the result is correct, but the function is same
    *** could anyone take a try and let me know why I get two different result??***


Log in to reply
 

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