Appearance
- K 个一组翻转链表
给你链表的头节点 head ,每 k 个节点一组进行翻转,请你返回修改后的链表。
k 是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。
你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。
示例 1:
输入:head = [1,2,3,4,5], k = 2
输出:[2,1,4,3,5]
示例 2:
输入:head = [1,2,3,4,5], k = 3
输出:[3,2,1,4,5]
提示:
链表中的节点数目为 n
1 <= k <= n <= 5000
0 <= Node.val <= 1000
进阶:你可以设计一个只用 O(1) 额外内存空间的算法解决此问题吗?
- 来源:力扣(LeetCode)
- 链接:https://leetcode.cn/problems/reverse-nodes-in-k-group
javascript
/**
* 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 a = b = head
for (let i = 0; i < k; i++) {
if(b === null) return head
b = b.next
}
const newHead = reverse(a, b)
a.next = reverseKGroup(b, k)
return newHead
}
function reverse(a, b){
let pre = null, cur = a, next = a
while(cur !== b){
next = cur.next
cur.next = pre
pre = cur
cur = next
}
return pre
}
// test
function ListNode(val, next) {
this.val = val === undefined ? 0 : val
this.next = next === undefined ? null : next
}
var l1 = new ListNode(1)
var lstNode1 = new ListNode(2)
var lstNode2 = new ListNode(3)
var lstNode3 = new ListNode(4)
l1.next = lstNode1
lstNode1.next = lstNode2
lstNode2.next = lstNode3
console.log(reverseKGroup(l1, 3))