Created
November 8, 2014 17:53
-
-
Save wszdwp/de6022d09f9614487278 to your computer and use it in GitHub Desktop.
Given a list, rotate the list to the right by k places, where k is non-negative. For example: Given 1->2->3->4->5->NULL and k = 2, return 4->5->1->2->3->NULL.
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 { | |
| public ListNode rotateRight(ListNode head, int n) { | |
| //http://fisherlei.blogspot.com/2013/01/leetcode-rotate-list.html | |
| if (n == 0 || head == null) | |
| return head; | |
| int len = 1; | |
| ListNode p = head; | |
| while (p.next != null) { | |
| p = p.next; | |
| len++; | |
| } | |
| if (n == len) | |
| return head; | |
| n = len - n % len; | |
| p.next = head; | |
| int step = 0; | |
| while (step < n) { | |
| p = p.next; | |
| step++; | |
| } | |
| head = p.next; | |
| p.next = null; | |
| return head; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment