For example, there is an arraylist: 40 8 6 3 7 5 2, and I want to left shift them by 2 post. And then expected output is 6 3 7 5 2. I have wrote the following code, but it generate nothing
Code: import java.util.ArrayList;
class ArrayLinearListRev extends ArrayLinearList{
public ArrayList<Integer> leftSh(int post, ArrayList<Integer>
alist2)
{
ArrayList<Integer> LeftshifedList = new ArrayList<Integer
();
for (int i = alist2.size(); i <= post; i++)
{
LeftshifedList.remove(alist2.get(i));
}
return LeftshifedList;
}
public void printElements(ArrayList<Integer> alist2)
{
for (int i = 0; i < alist2.size(); i++) {
System.out.print(alist2.get(i) + " ");
}
}
}
public class ArrayLinearListFun {
public static void main(String[] args)
{
ArrayLinearListRev obj = new ArrayLinearListRev();
ArrayList<Integer> x = new ArrayList<Integer>();
x.add(0, new Integer(2));
x.add(1, new Integer(5));
x.add(2, new Integer(7));
x.add(3, new Integer(3));
x.add(4, new Integer(6));
x.add(5, new Integer(8));
x.add(6, new Integer(40));
System.out.print("The list is: ");
obj.printElements(x);
x=obj.leftSh(2, x);
System.out.print("\nThe list is: ");
obj.printElements(x);
}
}
Your leftSh
method returns an empty List
. Assuming you don't want your method modify the original List
, you should initialize LeftshifedList
to be a copy of the original List
.
You simply need to remove the element at index 0
and repeat post
times.
public ArrayList<Integer> leftSh(int post, ArrayList<Integer> alist2)
{
ArrayList<Integer> LeftshifedList = new ArrayList<>(alist2); // create a copy of input List
for (int i = 1; i <= post; i++) { // remove the first post elements
LeftshifedList.remove(0);
}
return LeftshifedList;
}
Just remove first two elements.
public ArrayList<Integer> leftSh(int post, ArrayList<Integer> alist2) {
alist2.remove(0);
alist2.remove(0);
return alist2;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.