Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given
return
Given
1->2->3->4->5->NULL
and k = 2
,return
4->5->1->2->3->NULL
.
Solution:O(n)
public class Solution {
public ListNode rotateRight(ListNode head, int n) {
if(head == null || n==0 || head.next == null)
return head;
ListNode slow = head; ListNode fast = head; for(int i=0; i<n;i++){ fast = fast.next; if(fast == null) fast = head; } if(fast == slow) return head; while(fast.next!=null){ fast = fast.next; slow = slow.next; } ListNode ret = slow.next; slow.next = null; fast.next = head; return ret; } }
沒有留言:
張貼留言