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