For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.
題目大意:
給出一個單鏈表,和一個K值,根據K值往右旋轉,例如:
先求出鏈表的長度length,其實按着倒數第n%length個位置旋轉。
AC代碼:
public class Solution {
// public ListNode reverseList( ListNode head ){
// if( head == null || head.next == null )
// return head;
// ListNode p = head;
// ListNode q = head;
// while( q != null ){
// ListNode temp = q.next;
// q.next = p;
// p = q;
// q = temp;
// }
// head.next = null;
// head = p;
// return head;
// }
public ListNode rotateRight(ListNode head, int n){
if( head == null || head.next == null || n<=0 )
return head;
ListNode before = head;
ListNode after = head;
int length = 0;
while( before != null ){
length++;
before = before.next;
}
before = head;
// if( n > length ) return reverseList(head);
if( n%length == 0 ) return head;
for( int i=0; i<(n%length); i++ ){
after = after.next;
}
if( after == null ) return head;
while( after.next != null ){
before = before.next;
after = after.next;
}
ListNode temp = before.next;
before.next = null;
after.next = head;
head = temp;
return head;
}
}