Write the Java source code necessary to build a solution for the problem below:
ID: 3757109 • Letter: W
Question
Write the Java source code necessary to build a solution for the problem below:
Create a MyLinkedList class. Create methods in the class to add an item to the head, tail, or middle of a linked list; remove an item from the head, tail, or middle of a linked list; check the size of the list; and search for an element in the list.
Create a test class to use the newly created MyLinkedList class. Add the following names in to the list: James, John, Michael, Peter, Allison, Daniel, George, Simon, Jason, and Mark. Your program should allow the user to enter a name from the console, and then search to see if the name exists in the list.
Explanation / Answer
import java.util.*;
import java.util.Scanner;
class MyLinkedList {
LinkedList<String> object = new LinkedList<String>();
// add
public void add(String val) {
object.add(val);
System.out.println("Linked list : " + object);
}
// adding at head
public void addAtHead(String val) {
object.addFirst(val);
System.out.println("Linked list : " + object);
}
// adding at tail
public void addAtTail(String val) {
object.addLast(val);
System.out.println("Linked list : " + object);
}
// search
public void search(String val) {
boolean status = object.contains(val);
if (status)
System.out.println("List contains the element: " + val);
else
System.out.println("List doesn't contain the element: " + val);
}
public void removeAtHead() {
object.removeFirst();
System.out.println("Linked list After removing from Head : " + object);
}
public void removeAtTail() {
object.removeLast();
System.out.println("Linked list After removing from Tail : " + object);
}
public void mllSize() {
int size = object.size();
System.out.println("Size of linked list = " + size);
}
}
public class Test {
public static void main(String arg[]) {
MyLinkedList mll = new MyLinkedList();
mll.add("James");
mll.add("John");
mll.add("Michael");
mll.add("Peter");
mll.add("Allison");
mll.add("Daniel");
mll.add("George");
mll.add("Simon");
mll.add("Jason");
mll.add("Mark");
Scanner in = new Scanner(System.in);
System.out.println("Enter value that to add at Head");
String addValAtHead = in.nextLine();
mll.addAtHead(addValAtHead);
System.out.println("Enter value that to add at Tail");
String addValAtTail = in.nextLine();
mll.addAtTail(addValAtTail);
System.out.println("Enter value to Search");
String searchVal = in.nextLine();
mll.search(searchVal);
mll.mllSize();
System.out.println("Element After removing from head");
mll.removeAtHead();
System.out.println("Enter After removing from Tail");
mll.removeAtTail();
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.