Description
Given a linked list, rotate the list to the right by k places, where k is non-negative.
Examples
Example 1:
Input: 1->2->3->4->5->NULL, k = 2
Output: 4->5->1->2->3->NULL
Explanation:
rotate 1 steps to the right: 5->1->2->3->4->NULL
rotate 2 steps to the right: 4->5->1->2->3->NULL
Example 2:
Input: 0->1->2->NULL, k = 4
Output: 2->0->1->NULL
Explanation:
rotate 1 steps to the right: 2->0->1->NULL
rotate 2 steps to the right: 1->2->0->NULL
rotate 3 steps to the right: 0->1->2->NULL
rotate 4 steps to the right: 2->0->1->NULL
解题思路
首先第一步是要重新定位 kkk,因为可以循环,所以需要重置 kkk 的值,如对于一个长度为 555 的链表来说,k=2k = 2k=2 和 k=7k = 7k=7 的效果是一样的。
那么在定位 kkk 的时候,由于需要用到链表长度,所以可以获得 nullnullnull 前最后一个节点。
一个长度为7的链表,向右移动5位,通过观察可以得到
| 转换前 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|
| 转换后 | 3 | 4 | 5 | 6 | 7 | 1 | 2 |
关键点在于黄色标注的位置。
其中需要令 headnew=[3]head_{new} = [3]headnew=[3],[7].next=headprevious[7].next = head_{previous}[7].next=headprevious,[2].next=null[2].next = null[2].next=null
这几个位置也很好获得,[2][2][2] 的位置可以通过 length−klength - klength−k 获得,[3][3][3] 的位置可以通过 [2].next[2].next[2].next 获得, [7][7][7] 的位置可以通过遍历链表计算 lengthlengthlength 的时候获得
那么对于获得的节点,直接修改 nextnextnext 指针即可。
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if(head == null)
return head;
ListNode a, b, temp;
a = head;
b = head;
int i, n;
n = 0;
while(a.next != null){
n++;
a = a.next;
}
n++;
if((k % n == 0) || (n == 0))
return head;
k = (n - 1) - (k % n);
for(i = 0; i < k; i++){
b = b.next;
}
temp = b.next;
a.next = head;
b.next = null;
return temp;
}
}
本文详细解析了链表旋转算法的实现过程,包括如何通过调整链表节点的next指针来实现链表的右旋转。文章提供了具体示例,如输入1->2->3->4->5->NULL, k=2时的输出为4->5->1->2->3->NULL,并附带了完整的代码实现。
525

被折叠的 条评论
为什么被折叠?



