Description:
Given a linked list, rotate the list to the right by k places, where k is non-negative.
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来说,有三种可能的情况
- k == 0 || k % 链表的长度 == 0:无需旋转
- 0 <\lt< k <\lt< 链表的长度
- k >\gt> 链表的长度,将k对链表的长度取模,得到的是第二种情况
综上,我们所需要处理的仅仅是第二种情况;首先,遍历链表得到链表的长度lenlenlen;为了旋转最右端的k个节点,我们需要找到倒数第k+1个节点(即要旋转的那部分节点的开始节点的前一个节点),利用两个相距kkk个节点的指针遍历链表,直到最右端节点到达尾部;最后,把右端那部分节点与左端那部分节点调换位置;
例如,对于1->2->3->4->5->NULL, k = 2
找到右端要旋转的那部分节点的最左端节点的前一个节点位置preprepre和最后一个节点的位置headheadhead,vHead为虚拟头结点;
交换左右两部分节点;
java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if (head == null || k == 0) {
return head;
}
ListNode vHead = new ListNode(0);
vHead.next = head;
ListNode pre = vHead;
int len = 0;
while (head != null) {
len++;
head = head.next;
}
k %= len;
head = vHead;
for (int i = 0; i < k; i++) {
head = head.next;
}
while (head.next != null) {
pre = pre.next;
head = head.next;
}
head.next = vHead.next;
vHead.next = pre.next;
pre.next = null;
return vHead.next;
}
}