LeetCode-25. Reverse Nodes in K-Group

问题描述

Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list.

k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.

You may not alter the values in the list’s nodes, only nodes themselves may be changed.

Example:

1
2
Input: head = [1,2,3,4,5], k = 2
Output: [2,1,4,3,5]

Constraints:

  • The number of nodes in the list is n.
  • 1 <= k <= n <= 5000
  • 0 <= Node.val <= 1000

解答

方法一:递归
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/*
* @Description: 链表中的节点每k个一组翻转
* @Author: libk
* @Github: https://github.com/libk
*/
/**
* 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}
*/
const reverseKGroup = function (head, k) {
let tail = head
for (let i = 0; i < k; i++) {
if (tail === null) {
return head
}
tail = tail.next
}

let pre = null
let cur = head
while (cur !== tail) {
let temp = cur.next
cur.next = pre
pre = cur
cur = temp
}
head.next = reverseKGroup(tail, k)
return pre
}
方法二:迭代反转每一组子链表
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
* @param {ListNode} head
* @param {number} k
* @return {ListNode}
*/
let reverseKGroup2 = function (head, k) {
let length = getLength(head)
let newHead = head
for (let i = 1; (i + k - 1) <= length; i += k) {
newHead = reverseBetween(newHead, i, i + k - 1)
}
return newHead
}

function getLength (head) {
let n = 0
let cur = head
while (cur !== null) {
cur = cur.next
n++
}
return n
}

function reverseBetween (head, left, right) {
let dummy = new ListNode(-1)
dummy.next = head
let pre = dummy
let cur = head
for (let i = 1; i < left; i++) {
pre = cur
cur = cur.next
}
for (let j = left; j < right; j++) {
let temp = cur.next
cur.next = temp.next
temp.next = pre.next
pre.next = temp
}
return dummy.next
}