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.
Subscribe to see which companies asked this question.
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode rotateRight(ListNode head, int k) { ArrayList<Integer> list=new ArrayList<>(); ListNode temp=head; while(temp!=null){ list.add(temp.val); temp=temp.next; } temp=head; if(k>list.size()&&list.size()>0){ k=k%list.size(); } if(k<list.size()){ for(int i=list.size()-k;i<list.size();i++){ temp.val=list.get(i); temp=temp.next; } for(int i=0;i<list.size()-k;i++){ temp.val=list.get(i); temp=temp.next; } } return head; } }