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
.
思路:画图。
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 /** 14 * @param head: the List 15 * @param k: rotate to the right k places 16 * @return: the list after rotation 17 */ 18 public ListNode rotateRight(ListNode head, int k) { 19 if (head == null || head.next == null) { 20 return head; 21 } 22 23 ListNode dummy = new ListNode(0); 24 dummy.next = head; 25 ListNode node = dummy; 26 int length = 0; 27 while (node.next != null) { 28 ++length; 29 node = node.next; 30 } 31 node = dummy; 32 for (int i = 0; i < length - (k % length); i++) { 33 node = node.next; 34 } 35 ListNode tail = node; 36 while (tail.next != null) { 37 tail = tail.next; 38 } 39 tail.next = dummy.next; 40 dummy.next = node.next; 41 node.next = null; 42 return dummy.next; 43 } 44 }
原文:http://www.cnblogs.com/FLAGyuri/p/5423864.html