Problem:
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
.
Solution: Just Note that should count the length first, and rotate the list to the right by n % length places.
Code:
/**
* 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) {
if (head == null) return head;
int length = 0;
ListNode forCount = head;
ListNode newHead = new ListNode(0);
ListNode last = newHead;
newHead.next = head;
while(forCount != null) {
length++;
forCount = forCount.next;
last = last.next;
}
int k = n % length;
if (k == 0 || (head.next == null && k == 1)) return head;
int step= length - k;
ListNode current = newHead;
for (int i = 0; i < step; i++) {
current = current.next;
}
ListNode next = current.next;
current.next = null;
last.next = newHead.next;
return next;
}
}