Javascript程序以块方式旋转链接列表
给定一个长度为 n 和块长度为k的链表,每个块以循环方式向右/向左旋转一个数字d 。如果d为正,则向右旋转,否则向左旋转。
例子:
Input: 1->2->3->4->5->6->7->8->9->NULL,
k = 3
d = 1
Output: 3->1->2->6->4->5->9->7->8->NULL
Explanation: Here blocks of size 3 are
rotated towards right(as d is positive)
by 1.
Input: 1->2->3->4->5->6->7->8->9->10->
11->12->13->14->15->NULL,
k = 4
d = -1
Output: 2->3->4->1->6->7->8->5->10->11
->12->9->14->15->13->NULL
Explanation: Here, at the end of linked
list, remaining nodes are less than k, i.e.
only three nodes are left while k is 4.
Rotate those 3 nodes also by d.
先决条件:旋转链表
这个想法是如果 d 的绝对值大于 k 的值,则将链表旋转 d % k 次。如果 d 为 0,则根本不需要旋转链表。
Javascript
输出:
Given linked list
1 2 3 4 5 6 7 8 9
Rotated by blocks Linked list
2 3 1 5 6 4 8 9 7
有关详细信息,请参阅有关 Rotate Linked List 块的完整文章!