leetcode 25. K 个一组翻转链表
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ /** * @param {ListNode} head * @param {number} k * @return {ListNode} */ var reverseKGroup = function(head, k) { let cnt = 0; let curp = head; while(curp){ cnt++; curp = curp.next; if(cnt>=k){ break; } } if(cnt<k){ return head; }else{ let newson = head; let newfa = head.next; let oldfa = null; let cnt = k; while(--cnt){ let tem = newfa.next; newfa.next = newson; newson.next = oldfa; oldfa = newson; newson = newfa; newfa = tem; } head.next = reverseKGroup(newfa,k); return newson; } }
该题本质上是翻转链表的变体。
解法需要结合 递归+翻转链表。代码思路还是非常清晰的。