Because k may be greater the length of the list, we need to caculate the length of the list first. Then we can say rotate the list by (k % length) places. Next, we Link the head and tail of the list as a circle. Continuely, go through (length - k % length) places, and break the connection at that node.
> File Name: RotateList.java > Author: Yao Zhang > Mail: [email protected] > Created Time: Wed 18 Nov 16:47:13 2015 ************************************************************************/
publicclass{ public ListNode rotateRight(ListNode head, int k){ if (head == null) return head; int length = 1; ListNode current = head; while (current.next != null){ length++; current = current.next; } current.next = head; k = length - k % length ; while (k > 0){ current = current.next; k--; } head = current.next; current.next = null; return head; } }
近期评论