In: Computer Science
This LinkedListUtil class tests various usages of the LinkedList class. The single param is an array of string. You will create a linked list with the string elements and return the linked list with all but the 1st two elements removed.
Note: In this question use a for or while loop instead of the suggested iterator. You should also ignore CodeCheck’s error message about a missing class (LinkedListUtil.class). Your code still needs to pass all test cases.
EDIT: For clarifcation you want to remove all besides the first 2 elements. So only the first 2 elements should be returned
LinkedListUtil.java
import java.util.LinkedList;
import java.util.ListIterator;
/**
This LinkedListUtil class tests various usages of the LinkedList
class
*/
public class LinkedListUtil
{
/**
Constructs a LinkedListUtil.
@param list is the initialized list
*/
public LinkedListUtil(LinkedList list)
{
this.list = list;
}
/**
deletes all but the first two linked list enries
*/
public void processList()
{
// TODO: create a list iterator and remove all but the first two
elements
}
private LinkedList list;
// this method is used to check your work
public static LinkedList check(String[] values)
{
LinkedList list = new LinkedList();
for (String s : values)
list.addLast(s);
LinkedListUtil tester = new LinkedListUtil(list);
tester.processList();
return list;
}
}
Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. If not, PLEASE let me know before you rate, I’ll help you fix whatever issues. Thanks
//LinkedListUtil.java
import java.util.LinkedList;
import java.util.ListIterator;
/**
* This LinkedListUtil class tests various usages of the LinkedList class
*/
public class LinkedListUtil {
/**
* Constructs a LinkedListUtil.
*
* @param list
* is the initialized list
*/
public LinkedListUtil(LinkedList list) {
this.list = list;
}
/**
* deletes all but the first two linked list enries
*/
public void processList() {
// looping as long as list is not null and list has more than 2
// elements.
// note: I am using while loop instead of an iterator as mentioned in
// the question description.
while (list != null && list.size() > 2) {
// removing last element
list.removeLast();
}
}
private LinkedList list;
// this method is used to check your work
public static LinkedList check(String[] values) {
LinkedList list = new LinkedList();
for (String s : values)
list.addLast(s);
LinkedListUtil tester = new LinkedListUtil(list);
tester.processList();
return list;
}
}