Rotate List
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.
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) return head; 20 // write your code here 21 int size = size(head); 22 k = k % size; 23 24 if (k == 0) return head; 25 ListNode pointer = head; 26 for (int i = 1; i <= size - k - 1; i++) { 27 pointer = pointer.next; 28 } 29 30 ListNode newHead = pointer.next; 31 pointer.next = null; 32 33 // link the tail to the head 34 ListNode current = newHead; 35 while (current.next != null) { 36 current = current.next; 37 } 38 current.next = head; 39 return newHead; 40 } 41 42 public int size(ListNode head) { 43 int count = 0; 44 while (head != null) { 45 count++; 46 head = head.next; 47 } 48 return count; 49 } 50 }
转载请注明出处:cnblogs.com/beiyeqingteng/