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.
Java code
Complete the following file:
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<String> 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<String> list;
// this method is used to check your work
public static LinkedList<String> check(String[] values)
{
LinkedList<String> list = new
LinkedList<String>();
for (String s : values)
list.addLast(s);
LinkedListUtil tester = new LinkedListUtil(list);
tester.processList();
return list;
}
}
Program Code Screenshot :
Sample Output :
Program Code to Copy
import java.util.Iterator; import java.util.LinkedList; /** This LinkedListUtil class tests various usages of the LinkedList class */ class LinkedListUtil { /** Constructs a LinkedListUtil. @param list is the initialized list */ public LinkedListUtil(LinkedList<String> 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 //Create an iterator Iterator i = this.list.iterator(); //Skip 2 elements i.next(); i.next(); //Remove all the other elements while (i.hasNext()){ i.next(); i.remove(); } } private LinkedList<String> list; // this method is used to check your work public static LinkedList<String> check(String[] values) { LinkedList<String> list = new LinkedList<String>(); for (String s : values) list.addLast(s); LinkedListUtil tester = new LinkedListUtil(list); tester.processList(); return list; } } class Main{ public static void main(String[] args) { //Invoke the function with the Strings "a","b","c" and "d" LinkedList<String> linkedList = LinkedListUtil.check(new String[]{"a","b","c","d","e","f"}); System.out.println(linkedList); } }