Created
September 2, 2015 17:44
-
-
Save cxtadment/6bb93514c6865a591f72 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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) { | |
| // write your code here | |
| if (head == null || k == 0) { | |
| return head; | |
| } | |
| int length = getLength(head); | |
| ListNode newHead = null; | |
| ListNode preMarkHead = head; | |
| k = k % length; | |
| if (k == 0) { | |
| return head; | |
| } | |
| for (int i = 1; i < length - k; i++) { | |
| head = head.next; | |
| } | |
| newHead = head.next; | |
| ListNode reverseHead = head.next; | |
| head.next = null; | |
| while (reverseHead.next != null) { | |
| reverseHead = reverseHead.next; | |
| } | |
| reverseHead.next = preMarkHead; | |
| return newHead; | |
| } | |
| private int getLength(ListNode head) { | |
| int size = 0; | |
| while (head != null) { | |
| size++; | |
| head = head.next; | |
| } | |
| return size; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment