[Java] Please test your code in the link I provide before you post your answer.
ID: 3830111 • Letter: #
Question
[Java] Please test your code in the link I provide before you post your answer.
The output should be looked like exact same as the tester.
http://www.codecheck.it/files/17033122188mcxvjz8n8qbk0k9fyfrd3w95
Thank you.
Write a class LinkedListUtil that contains 2 static methods
public static void shrink(LinkedList<String> strings, int n) removes every nth node in the LinkedList of Strings. Start the removal with the nth not the 0th node
public static LinkedList<String> reverse(LinkedList<String> strings) return a LinkedList in which the the order of the elements is reversed.
Use the following file:
LinkedListUtilTester.java
Explanation / Answer
Here is your code below. There was one issue I found out in your expected for the second part. You didn't deleted the last element, but deleted the nth element from last first. But in first part of your problem you deleted the last one first and then deleted each nth element.
LinkedListUtil.java
import java.util.LinkedList;
public class LinkedListUtil {
public static void shrink(LinkedList<String> strings, int n) {
int size = strings.size();
if(size%n == 0) { // checking if last element is divisible by n
for (int i = size-1; i >= 0;) {
strings.remove(i);
i=i-n;
}
} else {
// this is done because your one output was deleting last element and then go on to delete each next n,
//but other one started with deleting first nth element and so on not deleting the last element.
for (int i = size-n; i >= 0;) {
strings.remove(i);
i=i-n;
}
}
}
public static LinkedList<String> reverse(LinkedList<String> strings) {
int length = strings.size();
for (int i = 0; i < length / 2; i++) {
String as = (String)strings.get(i);
strings.set(i, strings.get(length - 1 - i));//setting each element i from first to each element i from last
strings.set(length - 1 - i, as);
}
return strings;
}
}
Sample Run: -
[1, 2, 4, 5, 7, 8, 10, 11, 13, 14]
Expected: [1, 2, 4, 5, 7, 8, 10, 11, 13, 14]
[14, 13, 11, 10, 8, 7, 5, 4, 2, 1]
Expected: [14, 13, 11, 10, 8, 7, 5, 4, 2, 1]
[uno, dos, tres, cinco, seis, siete, nueve, dies, once, trece, catorce, quince]
Expected: [uno, dos, tres, cinco, seis, siete, nueve, dies, once, trece, catorce, quince]
[quince, catorce, trece, once, dies, nueve, siete, seis, cinco, tres, dos, uno]
Expected: [quince, catorce, trece, once, dies, nueve, siete, seis, cinco, tres, dos, uno]
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.