Write a Java static method circulate which takes an ArrayList and creates a shif
ID: 3880011 • Letter: W
Question
Write a Java static method circulate which takes an ArrayList and creates a shifted copy of it. Circulate shifts all elements forward in the list to a new position based on the integer parameter index. If the elements shift off the end of the list, they wrap around to the beginning. Here is the header for this method: ArrayListInteger» Circulate (ArrayListInteger» list, int index) You can assume that parameters list is not null and index is non-negative. Here are some examples: A. If the passed list is: [0, 1, 2, 3, 4, 5] and index = 2, the returned list will be: [4, 5, 0, 1, 2, 3] B. If the passed list is: [0, 1, 2, 3, 4, 5] and index = 6, the returned list will be: [e, 1, 2, 3, 4, 5] C. If the passed list is: [0, 1, 2, 3, 4, 5] and index = 5, the returned list will be: [1, 2, 3, 4, 5, 0]?Explanation / Answer
/*There are 2-3 approaches to solve this problem
* if length of list is n and you want to rotate k time then
* first check if k>n then k=k%n so k will always be less than n
* Solution (1)
* steps:(1) copy n-k elements to the another arraylist called temp
* (2) then shift last k element to to beginning of the original list
* (3) finally copy content to temp arraylist to the original list after k elements
*
* Solution(2):
*
* Since given data structure is arraylist which is dynamic in nature so we can do
* insert and delete operation frequently
* So we will do n-k insert delete operations on list and we can achieve our desire result
* we will remove from front and add the same removed element at last
*
* */
//Method to circulate
static ArrayList<Integer> circulate(ArrayList<Integer> list,int index)
{
int n=list.size();
if(index>n)
index=index%n;
//n-index insert and delete operations
for(int i=1;i<=n-index;i++)
{
//removing first element and adding at last
int x=list.remove(0);
list.add(x);
}
return list;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.