leetcode javascript版 25. k个一组翻转链表

暂时没有想到好方案,就用遍历链表写了一个。

var reverseKGroup = function(head, k) {
    var prev = null;
    var curr = head;
    var p1 = null;  
    var p2 = null;
    while(curr !== null) {
        for(var i = 0; i < k; i++) { 
            if(curr === null) {
                return head;
            }
            curr = curr.next;
        }
        p1 = (prev)? prev.next: head;
        p2 = p1.next;
        for(var i = 0; i < k - 1; i++) {
            var next = p2.next;
            p2.next = p1;
            p1 = p2;
            p2 = next;
        }
        if(!prev) {
            prev = head;
            head.next = curr;
            head = p1;
        } else {
            var tempPrev = prev.next;
            prev.next.next = curr;
            prev.next = p1;
            prev = tempPrev;
        }
    }

    return head;
};

你可能感兴趣的:(leetCode刷题记录)