I'm new to coding and I'm trying to Iterate a linkedlist. The below is the question: Create a Linkedlist having elements ranging from 1 to 8. I need to reverse the list but with one condition i.e., if the num is given as 2. The output should be produced in the following way: [2,1,4,3,6,5,8,7].
Please find the code below. I tried and able to get the respective answer if num is either 2 or 4.
LinkedList<Integer> list = new LinkedList<>();
for (int i = 1; i < 9; i ) {
list.add(i);
}
int n = 2;
LinkedList<Integer> outList = new LinkedList<>();
while(list.size()>0) {
for(int i=n-1;i>=0;i--) {
outList.add(list.get(i));
list.remove(i);
}
}
System.out.println(outList);
I don't know whether this is the appropriate way. Please help me with the appropriate solution.
The problem I'm facing is if I give num as 3. I'm getting IndexOutOfBoundsException as there are only 2 elements in the last iteration.
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
at java.base/java.util.LinkedList.checkElementIndex(LinkedList.java:559)
at java.base/java.util.LinkedList.get(LinkedList.java:480)
at com.src.User.main(User.java:21)
CodePudding user response:
It can be added to list(like a queue) and then retrieved from the rear side(like a stack). So it doesnt require an index.
LinkedList<Integer> list = new LinkedList<>();
for (int i = 1; i < 9; i ) {
list.addLast(i);
}
int n = 2;
System.out.println(list);
LinkedList<Integer> outList = new LinkedList<>();
while(list.size()>0) {
outList.addLast(list.removeLast());//last element retrieved first
}
System.out.println(outList);
CodePudding user response:
Could you please paste the problem description also? I am not sure if it is clear from your question what problem you are trying to solve.
