update: K个一组翻转链表

This commit is contained in:
yi-ge 2020-05-16 20:46:41 +08:00
parent 55ff39a1c3
commit a3c4f1b9fc

View File

@ -11,33 +11,31 @@
* @return {ListNode} * @return {ListNode}
*/ */
export const reverseKGroup = function (head, k) { export const reverseKGroup = function (head, k) {
let sum = 0 let sum = 0 // 记录进行的结点个数
let start = head let start = head // 记录每次翻转的第一个元素
let newStart = head let res = head // 返回值:如果进行过翻转,则为第一次翻转的最后一个结点
let first = true const queue = [] // 使用队列方便连接上一次翻转的链表最大长度为2
const last = [] while (head) { // 遍历一次链表
while (head) { if (++sum === k) { // 如果经过了k个结点则翻转从start到head的一段结点
if (++sum === k) {
const headNext = head.next const headNext = head.next
last.push(start) queue.push(start) // 计入队列
let next = head.next let next = head.next
for (let i = 0; i < sum - 1; i++) { for (let i = 0; i < sum - 1; i++) { // 翻转结点
const tmp = start.next const tmp = start.next
start.next = next start.next = next
next = start next = start
start = tmp start = tmp
} }
start.next = next start.next = next // 最后一个结点
if (first) { if (queue.length === 1) { // 判断是否为第一次翻转
newStart = start res = start
first = false
} else { } else {
const la = last.shift() const la = queue.shift() // 连接上一次翻转的链表
la.next = head la.next = head
} }
sum = 0 sum = 0 // 重置计数
start = headNext start = headNext
head = headNext head = headNext
} else { } else {
@ -45,5 +43,5 @@ export const reverseKGroup = function (head, k) {
} }
} }
return newStart return res
} }