Question
Please write comment
solve the problem by implementing the whole class with main() function and demonstrate that your Java code can pass several appropriate test cases successfully in your main() function
Problem:
Implement a method with signature concatenate(LinkedQueue<E> Q2) for the
LinkedQueue<E> class that takes all elements of Q2 and appends them to the
end of the original queue. The operation should run in O(1) time and should
result in Q2 being an empty queue.
Explanation / Answer
import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; public class MyLinkedList implements List { private class Node { public E cargo; public Node next; public Node(E cargo) { this.cargo = cargo; this.next = null; } public Node(E cargo, Node next) { this.cargo = cargo; this.next = next; } public String toString() { return "Node(" + cargo.toString() + ")"; } } private int size; // keeps track of the number of elements private Node head; // reference to the first node public MyLinkedList() { head = null; size = 0; } public static void main(String[] args) { // run a few simple tests List mll = new MyLinkedList(); mll.add(1); mll.add(2); mll.add(3); System.out.println(Arrays.toString(mll.toArray()) + " size = " + mll.size()); mll.remove(new Integer(2)); System.out.println(Arrays.toString(mll.toArray()) + " size = " + mll.size()); } @Override public boolean add(E element) { if (head == null) { head = new Node(element); } else { Node node = head; // loop until the last node for ( ; node.next != null; node = node.next) {} node.next = new Node(element); } size++; return true; } @Override public void add(int index, E element) { // no need to check bounds; getNode does it. if (index == 0) { head = new Node(element, head); } else { Node node = getNode(index-1); node.next = new Node(element, node.next); } size++; } @Override public boolean addAll(Collection collection) { for (Object obj: collection) { if (!contains(obj)) { return false; } } return true; } @Override public E get(int index) { Node node = getNode(index); return node.cargo; } private Node getNode(int index) { if (index < 0 || index >= size) { throw new IndexOutOfBoundsException(); } Node node = head; for (int i=0; i