2017.9.7
首先计算出链表的长度size。
向右移k 等价于向右 移 k%size,等价于向左移 size - k%size。
基于此,相当于将链表划分为两个链表,再交换位置相连成为一个链表。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* @param head: the List
* @param k: rotate to the right k places
* @return: the list after rotation
*/
public static ListNode rotateRight(ListNode head, int k) {
// write your code here
ListNode flag = head;
if(head == null){
return head;
}
int size = 1;
while(flag.next != null){
size++;
flag = flag.next;
}
k = k%size;
if(k == 0){
return head;
}
k = size - k;
ListNode newTail = new ListNode(0);
newTail.next = head;
ListNode newHead = head;
while(k > 0){
k--;
newTail = newTail.next;
newHead = newHead.next;
}
flag.next = head;
newTail.next = null;
head = newHead;
return head;
}
}