这是我参与8月更文挑战的第25天,活动详情查看:8月更文挑战
leetcode-cn好像又挂了,用英文吧
题目
Given a linked list, reverse the nodes of a linked list k at a time and return its 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:
Input: head = [1,2,3,4,5], k = 2 Output: [2,1,4,3,5]
Example 2:
Input: head = [1,2,3,4,5], k = 3
Output: [3,2,1,4,5]
Example 3:
Input: head = [1,2,3,4,5], k = 1
Output: [1,2,3,4,5]
Example 4:
Input: head = [1], k = 1
Output: [1]
Constraints:
- The number of nodes in the list is in the range
sz. 1 <= sz <= 50000 <= Node.val <= 10001 <= k <= sz
Follow-up: Can you solve the problem in O(1) extra memory space?
解题思路
题意是以 k 个nodes为一组进行翻转,返回翻转后的linked list.
从左往右扫描一遍linked list,扫描过程中,以k为单位把数组分成若干段,对每一段进行翻转。给定首尾nodes,如何对链表进行翻转。
链表的翻转过程,初始化一个为null 的 previous node(prev),然后遍历链表的同时,当前node (curr)的下一个(next)指向前一个node(prev),
在改变当前node的指向之前,用一个临时变量记录当前node的下一个node(curr.next). 即
ListNode temp = curr.next; curr.next = prev; prev = curr; curr = temp;
举例如图:翻转整个链表 1->2->3->4->null -> 4->3->2->1->null
这里是对每一组(k个nodes)进行翻转,
-
先分组,用一个
count变量记录当前节点的个数 -
用一个
start变量记录当前分组的起始节点位置的前一个节点 -
用一个
end变量记录要翻转的最后一个节点位置 -
翻转一组(
k个nodes)即(start, end) \- start and end exclusively。 -
翻转后,
start指向翻转后链表, 区间(start,end)中的最后一个节点, 返回start节点。 -
如果不需要翻转,
end就往后移动一个(end=end.next),每一次移动,都要count+1.
如图所示 步骤4和5: 翻转区间链表区间(start, end)
举例如图,head=[1,2,3,4,5,6,7,8], k = 3
NOTE: 一般情况下对链表的操作,都有可能会引入一个新的
dummy node,因为head有可能会改变。这里head 从1->3,
dummy (List(0))保持不变。
复杂度分析
- 时间复杂度:
O(n) - n is number of Linked List - 空间复杂度:
O(1)
关键点分析
- 创建一个dummy node
- 对链表以k为单位进行分组,记录每一组的起始和最后节点位置
- 对每一组进行翻转,更换起始和最后的位置
- 返回
dummy.next.
代码
/**
* @param {ListNode} head
* @param {number} k
* @return {ListNode}
*/
var reverseKGroup = function(head, k) {
// 标兵
let dummy = new ListNode()
dummy.next = head
let [start, end] = [dummy, dummy.next]
let count = 0
while(end) {
count++
if (count % k === 0) {
start = reverseList(start, end.next)
end = start.next
} else {
end = end.next
}
}
return dummy.next
// 翻转stat -> end的链表
function reverseList(start, end) {
let [pre, cur] = [start, start.next]
const first = cur
while(cur !== end) {
let next = cur.next
cur.next = pre
pre = cur
cur = next
}
start.next = pre
first.next = cur
return first
}
};
扩展
-
要求从后往前以
k个为一组进行翻转。(字节跳动(ByteDance)面试题)例子,
1->2->3->4->5->6->7->8, k = 3,从后往前以
k=3为一组,6->7->8为一组翻转为8->7->6,3->4->5为一组翻转为5->4->3.1->2只有2个nodes少于k=3个,不翻转。
最后返回:
1->2->5->4->3->8->7->6
这里的思路跟从前往后以k个为一组进行翻转类似,可以进行预处理:
-
翻转链表
-
对翻转后的链表进行从前往后以k为一组翻转。
-
翻转步骤2中得到的链表。
例子:1->2->3->4->5->6->7->8, k = 3
-
翻转链表得到:
8->7->6->5->4->3->2->1 -
以k为一组翻转:
6->7->8->3->4->5->2->1 -
翻转步骤#2链表:
1->2->5->4->3->8->7->6
最后
曾梦想仗剑走天涯
看一看世界的繁华
年少的心总有些轻狂
终究不过是个普通人
无怨无悔我走我路
「前端刷题」No.25