add: K个一组翻转链表

This commit is contained in:
yi-ge 2020-05-16 19:50:31 +08:00
parent 5593f3e2c7
commit 55ff39a1c3
4 changed files with 75 additions and 0 deletions

View File

@ -411,3 +411,8 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重
- LeetCode 876. 链表的中间结点 <https://leetcode-cn.com/problems/middle-of-the-linked-list/>
- LintCode 1609. 链表的中间结点 <https://www.lintcode.com/problem/middle-of-the-linked-list/description>
- [K个一组翻转链表](src/list/reverse-nodes-in-k-group.js)
- LeetCode 25. K 个一组翻转链表 <https://leetcode-cn.com/problems/reverse-nodes-in-k-group/>
- LintCode 450. K组翻转链表 <https://www.lintcode.com/problem/reverse-nodes-in-k-group/>

View File

@ -0,0 +1,49 @@
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @param {number} k
* @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) {
const headNext = head.next
last.push(start)
let next = head.next
for (let i = 0; i < sum - 1; i++) {
const tmp = start.next
start.next = next
next = start
start = tmp
}
start.next = next
if (first) {
newStart = start
first = false
} else {
const la = last.shift()
la.next = head
}
sum = 0
start = headNext
head = headNext
} else {
head = head.next
}
}
return newStart
}

View File

@ -15,3 +15,13 @@ export const arrToList = (arr) => {
return head
}
export const listToArr = (list) => {
const arr = []
while (list) {
arr.push(list.val)
list = list.next
}
return arr
}

View File

@ -0,0 +1,11 @@
import { reverseKGroup } from '../../src/list/reverse-nodes-in-k-group'
import { arrToList, listToArr } from './ListNode'
test('K个一组翻转链表', () => {
const res = reverseKGroup(arrToList([1, 2, 3, 4, 5]), 3)
expect(listToArr(res)).toEqual([3, 2, 1, 4, 5])
expect(res).toEqual(arrToList([3, 2, 1, 4, 5]))
expect(reverseKGroup(arrToList([1, 2, 3, 4, 5]), 2)).toEqual(arrToList([2, 1, 4, 3, 5]))
expect(reverseKGroup(arrToList([1, 2, 3, 4, 5, 6]), 2)).toEqual(arrToList([2, 1, 4, 3, 6, 5]))
expect(reverseKGroup(arrToList([1, 2, 3, 4, 5, 6, 7, 8]), 2)).toEqual(arrToList([2, 1, 4, 3, 6, 5, 8, 7]))
})