题目:
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given 1->2->3->4->5->NULL
and k = 2
,
return 4->5->1->2->3->NULL
.
分析:
1. k的值可能大于链表的长度,因此先遍历链表,找到链表的长度length,k%length得到真正需要旋转的位数。
2. 如果得到k=0,则直接返回 原链表。
3. 需要找到三个位置,旋转开始节点的前一个节点,旋转开始的节点和链表的最后一个节点。 找这个三个节点的方法和Remove Nth Node From End of List题目的方法一样。用两个指针,快指针先走k-1步, 然后快慢指针一起向前每次走一步,找到快指针到达最后一个节点,刚好找到我们需要的旋转开始的节点和链表的最后一个节点。
Java代码实现:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode rotateRight(ListNode head, int k) {
if(head==null || head.next == null)
return head;
ListNode node = head;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;
int size = 0;
while(node!=null)
{
node = node.next;
size++;
}
k = k%size;
if(k==0)
return head;
ListNode fast = head;
ListNode slow = head;
for(int i=0;i<k-1;i++)
{
fast = fast.next;
}
while(fast.next!=null)
{
fast = fast.next;
slow = slow.next;
pre = pre.next;
}
pre.next = null;
dummy.next = slow;
fast.next = head;
return dummy.next;
}
}