Rotate List
把list往右旋转移动k个node. 这个就是用一个dummy记录一下head, 然后移动headk个单位,用tail记录当前的k个单位后的node, 然后同时移动, 后连起来即可.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public int len(ListNode head) { int len = 0; while(head != null){ len++; head = head.next; } return len; } public ListNode rotateRight(ListNode head, int k) { if(head == null) return null; k = k % len(head); ListNode dummy = new ListNode(0); dummy.next = head; head = dummy; ListNode tail = dummy; for(int i = 0 ; i < k; i++) { head = head.next; } while(head.next != null) { head = head.next; tail = tail.next; } head.next = dummy.next; dummy.next = tail.next; tail.next = null; return dummy.next; } } |