Given a list, rotate the list to the right by k
places, where k is non-negative.
Example
Given 1->2->3->4->5
and k = 2
, return 4->5->1->2->3
.
分析:
先得到list size, 然后 k = k % size. 找到新head,然后把tail链接到head.
/**
* 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 ListNode rotateRight(ListNode head, int k) {
if (head == null || head.next == null) return head;
// write your code here
int size = size(head);
k = k % size; if (k == ) return head;
ListNode pointer = head;
for (int i = ; i <= size - k - ; i++) {
pointer = pointer.next;
} ListNode newHead = pointer.next;
pointer.next = null; // link the tail to the head
ListNode current = newHead;
while (current.next != null) {
current = current.next;
}
current.next = head;
return newHead;
} public int size(ListNode head) {
int count = ;
while (head != null) {
count++;
head = head.next;
}
return count;
}
}
转载请注明出处:cnblogs.com/beiyeqingteng/