SlideShare a Scribd company logo
1 of 18
Download to read offline
Hi,
I have added the methods and main class as per your requirement. it is working fine now.
Highlighted the code changes.
MyLinkedListTest.java
public class MyLinkedListTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MyLinkedList list = new MyLinkedList();
list.addFirst("AAAAA");
list.add("1");
list.add("2");
list.add("3");
list.addLast("ZZZZZ");
System.out.println("Linked List Elements : "+list.toString());
System.out.println("First element: "+list.getFirst());
System.out.println("Second element: "+list.getLast());
System.out.println("Removed First Element: "+list.removeFirst());
System.out.println("Now Linked List Elements : "+list.toString());
System.out.println("Removed Last Element: "+list.removeLast());
System.out.println("Now Linked List Elements : "+list.toString());
System.out.println("Removed all element: ");
list.removeAll();
System.out.println("Now Linked List Elements : "+list.toString());
}
}
MyLinkedList.java
public class MyLinkedList extends MyAbstractList {
private Node head, tail;
/** Create a default list */
public MyLinkedList() {
}
/** Create a list from an array of objects */
public MyLinkedList(E[] objects) {
super(objects);
}
/** Return the head element in the list */
public E getFirst() {
if (size == 0) {
return null;
}
else {
return (E)head.element;
}
}
/** Return the last element in the list */
public E getLast() {
if (size == 0) {
return null;
}
else {
return (E)tail.element;
}
}
/** Add an element to the beginning of the list */
public void addFirst(E e) {
Node newNode = new Node(e); // Create a new node
newNode.next = head; // link the new node with the head
head = newNode; // head points to the new node
size++; // Increase list size
if (tail == null) // the new node is the only node in list
tail = head;
}
/** Add an element to the end of the list */
public void addLast(E e) {
Node newNode = new Node(e); // Create a new for element e
if (tail == null) {
head = tail = newNode; // The new node is the only node in list
}
else {
tail.next = newNode; // Link the new with the last node
tail = tail.next; // tail now points to the last node
}
size++; // Increase size
}
/** Add a new element at the specified index in this list
* The index of the head element is 0 */
public void add(int index, E e) {
if (index == 0) {
addFirst(e);
}
else if (index >= size) {
addLast(e);
}
else {
Node current = head;
for (int i = 1; i < index; i++) {
current = current.next;
}
Node temp = current.next;
current.next = new Node(e);
(current.next).next = temp;
size++;
}
}
/** Remove the head node and
* return the object that is contained in the removed node. */
public E removeFirst() {
if (size == 0) {
return null;
}
else {
Node temp = head;
head = head.next;
size--;
if (head == null) {
tail = null;
}
return (E)temp.element;
}
}
/** Remove all elements from list */
public void removeAll() {
while(true) {
if (size == 0) {
break;
}
else {
Node temp = head;
head = head.next;
size--;
if (head == null) {
tail = null;
}
}
}
}
/** Remove the last node and
* return the object that is contained in the removed node. */
public E removeLast() {
if (size == 0) {
return null;
}
else if (size == 1) {
Node temp = head;
head = tail = null;
size = 0;
return (E)temp.element;
}
else {
Node current = head;
for (int i = 0; i < size - 2; i++) {
current = current.next;
}
Node temp = tail;
tail = current;
tail.next = null;
size--;
return (E)temp.element;
}
}
/** Remove the element at the specified position in this list.
* Return the element that was removed from the list. */
public E remove(int index) {
if (index < 0 || index >= size) {
return null;
}
else if (index == 0) {
return removeFirst();
}
else if (index == size - 1) {
return removeLast();
}
else {
Node previous = head;
for (int i = 1; i < index; i++) {
previous = previous.next;
}
Node current = previous.next;
previous.next = current.next;
size--;
return (E)current.element;
}
}
/** Override toString() to return elements in the list */
public String toString() {
StringBuilder result = new StringBuilder("[");
Node current = head;
for (int i = 0; i < size; i++) {
result.append(current.element);
current = current.next;
if (current != null) {
result.append(", "); // Separate two elements with a comma
}
}
result.append("]"); // Insert the closing ] in the string
return result.toString();
}
/** Clear the list */
public void clear() {
head = tail = null;
}
/** Return true if this list contains the element o */
public boolean contains(E e) {
System.out.println("Implementation left as an exercise");
return true;
}
/** Return the element from this list at the specified index */
public E get(int index) {
System.out.println("Implementation left as an exercise");
return null;
}
/** Return the index of the head matching element in this list.
* Return -1 if no match. */
public int indexOf(E e) {
System.out.println("Implementation left as an exercise");
return 0;
}
/** Return the index of the last matching element in this list
* Return -1 if no match. */
public int lastIndexOf(E e) {
System.out.println("Implementation left as an exercise");
return 0;
}
/** Replace the element at the specified position in this list
* with the specified element. */
public E set(int index, E e) {
System.out.println("Implementation left as an exercise");
return null;
}
private static class Node {
E element;
Node next;
public Node(E element) {
this.element = element;
}
}
}
MyAbstractList.java
public abstract class MyAbstractList implements MyList {
protected int size = 0; // The size of the list
/** Create a default list */
protected MyAbstractList() {
}
/** Create a list from an array of objects */
protected MyAbstractList(E[] objects) {
for (int i = 0; i < objects.length; i++)
add(objects[i]);
}
/** Add a new element at the end of this list */
public void add(E e) {
add(size, e);
}
/** Return true if this list contains no elements */
public boolean isEmpty() {
return size == 0;
}
/** Return the number of elements in this list */
public int size() {
return size;
}
/** Remove the first occurrence of the element o from this list.
* Shift any subsequent elements to the left.
* Return true if the element is removed. */
public boolean remove(E e) {
if (indexOf(e) >= 0) {
remove(indexOf(e));
return true;
}
else
return false;
}
}
MyList.java
public interface MyList {
/** Add a new element at the end of this list */
public void add(E e);
/** Add a new element at the specified index in this list */
public void add(int index, E e);
/** Clear the list */
public void clear();
/** Return true if this list contains the element */
public boolean contains(E e);
/** Return the element from this list at the specified index */
public E get(int index);
/** Return the index of the first matching element in this list.
* Return -1 if no match. */
public int indexOf(E e);
/** Return true if this list contains no elements */
public boolean isEmpty();
/** Return the index of the last matching element in this list
* Return -1 if no match. */
public int lastIndexOf(E e);
/** Remove the first occurrence of the element o from this list.
* Shift any subsequent elements to the left.
* Return true if the element is removed. */
public boolean remove(E e);
/** Remove the element at the specified position in this list
* Shift any subsequent elements to the left.
* Return the element that was removed from the list. */
public E remove(int index);
/** Replace the element at the specified position in this list
* with the specified element and returns the new set. */
public Object set(int index, E e);
/** Return the number of elements in this list */
public int size();
}
Output:
Linked List Elements : [AAAAA, 1, 2, 3, ZZZZZ]
First element: AAAAA
Second element: ZZZZZ
Removed First Element: AAAAA
Now Linked List Elements : [1, 2, 3, ZZZZZ]
Removed Last Element: ZZZZZ
Now Linked List Elements : [1, 2, 3]
Removed all element:
Now Linked List Elements : []
Solution
Hi,
I have added the methods and main class as per your requirement. it is working fine now.
Highlighted the code changes.
MyLinkedListTest.java
public class MyLinkedListTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MyLinkedList list = new MyLinkedList();
list.addFirst("AAAAA");
list.add("1");
list.add("2");
list.add("3");
list.addLast("ZZZZZ");
System.out.println("Linked List Elements : "+list.toString());
System.out.println("First element: "+list.getFirst());
System.out.println("Second element: "+list.getLast());
System.out.println("Removed First Element: "+list.removeFirst());
System.out.println("Now Linked List Elements : "+list.toString());
System.out.println("Removed Last Element: "+list.removeLast());
System.out.println("Now Linked List Elements : "+list.toString());
System.out.println("Removed all element: ");
list.removeAll();
System.out.println("Now Linked List Elements : "+list.toString());
}
}
MyLinkedList.java
public class MyLinkedList extends MyAbstractList {
private Node head, tail;
/** Create a default list */
public MyLinkedList() {
}
/** Create a list from an array of objects */
public MyLinkedList(E[] objects) {
super(objects);
}
/** Return the head element in the list */
public E getFirst() {
if (size == 0) {
return null;
}
else {
return (E)head.element;
}
}
/** Return the last element in the list */
public E getLast() {
if (size == 0) {
return null;
}
else {
return (E)tail.element;
}
}
/** Add an element to the beginning of the list */
public void addFirst(E e) {
Node newNode = new Node(e); // Create a new node
newNode.next = head; // link the new node with the head
head = newNode; // head points to the new node
size++; // Increase list size
if (tail == null) // the new node is the only node in list
tail = head;
}
/** Add an element to the end of the list */
public void addLast(E e) {
Node newNode = new Node(e); // Create a new for element e
if (tail == null) {
head = tail = newNode; // The new node is the only node in list
}
else {
tail.next = newNode; // Link the new with the last node
tail = tail.next; // tail now points to the last node
}
size++; // Increase size
}
/** Add a new element at the specified index in this list
* The index of the head element is 0 */
public void add(int index, E e) {
if (index == 0) {
addFirst(e);
}
else if (index >= size) {
addLast(e);
}
else {
Node current = head;
for (int i = 1; i < index; i++) {
current = current.next;
}
Node temp = current.next;
current.next = new Node(e);
(current.next).next = temp;
size++;
}
}
/** Remove the head node and
* return the object that is contained in the removed node. */
public E removeFirst() {
if (size == 0) {
return null;
}
else {
Node temp = head;
head = head.next;
size--;
if (head == null) {
tail = null;
}
return (E)temp.element;
}
}
/** Remove all elements from list */
public void removeAll() {
while(true) {
if (size == 0) {
break;
}
else {
Node temp = head;
head = head.next;
size--;
if (head == null) {
tail = null;
}
}
}
}
/** Remove the last node and
* return the object that is contained in the removed node. */
public E removeLast() {
if (size == 0) {
return null;
}
else if (size == 1) {
Node temp = head;
head = tail = null;
size = 0;
return (E)temp.element;
}
else {
Node current = head;
for (int i = 0; i < size - 2; i++) {
current = current.next;
}
Node temp = tail;
tail = current;
tail.next = null;
size--;
return (E)temp.element;
}
}
/** Remove the element at the specified position in this list.
* Return the element that was removed from the list. */
public E remove(int index) {
if (index < 0 || index >= size) {
return null;
}
else if (index == 0) {
return removeFirst();
}
else if (index == size - 1) {
return removeLast();
}
else {
Node previous = head;
for (int i = 1; i < index; i++) {
previous = previous.next;
}
Node current = previous.next;
previous.next = current.next;
size--;
return (E)current.element;
}
}
/** Override toString() to return elements in the list */
public String toString() {
StringBuilder result = new StringBuilder("[");
Node current = head;
for (int i = 0; i < size; i++) {
result.append(current.element);
current = current.next;
if (current != null) {
result.append(", "); // Separate two elements with a comma
}
}
result.append("]"); // Insert the closing ] in the string
return result.toString();
}
/** Clear the list */
public void clear() {
head = tail = null;
}
/** Return true if this list contains the element o */
public boolean contains(E e) {
System.out.println("Implementation left as an exercise");
return true;
}
/** Return the element from this list at the specified index */
public E get(int index) {
System.out.println("Implementation left as an exercise");
return null;
}
/** Return the index of the head matching element in this list.
* Return -1 if no match. */
public int indexOf(E e) {
System.out.println("Implementation left as an exercise");
return 0;
}
/** Return the index of the last matching element in this list
* Return -1 if no match. */
public int lastIndexOf(E e) {
System.out.println("Implementation left as an exercise");
return 0;
}
/** Replace the element at the specified position in this list
* with the specified element. */
public E set(int index, E e) {
System.out.println("Implementation left as an exercise");
return null;
}
private static class Node {
E element;
Node next;
public Node(E element) {
this.element = element;
}
}
}
MyAbstractList.java
public abstract class MyAbstractList implements MyList {
protected int size = 0; // The size of the list
/** Create a default list */
protected MyAbstractList() {
}
/** Create a list from an array of objects */
protected MyAbstractList(E[] objects) {
for (int i = 0; i < objects.length; i++)
add(objects[i]);
}
/** Add a new element at the end of this list */
public void add(E e) {
add(size, e);
}
/** Return true if this list contains no elements */
public boolean isEmpty() {
return size == 0;
}
/** Return the number of elements in this list */
public int size() {
return size;
}
/** Remove the first occurrence of the element o from this list.
* Shift any subsequent elements to the left.
* Return true if the element is removed. */
public boolean remove(E e) {
if (indexOf(e) >= 0) {
remove(indexOf(e));
return true;
}
else
return false;
}
}
MyList.java
public interface MyList {
/** Add a new element at the end of this list */
public void add(E e);
/** Add a new element at the specified index in this list */
public void add(int index, E e);
/** Clear the list */
public void clear();
/** Return true if this list contains the element */
public boolean contains(E e);
/** Return the element from this list at the specified index */
public E get(int index);
/** Return the index of the first matching element in this list.
* Return -1 if no match. */
public int indexOf(E e);
/** Return true if this list contains no elements */
public boolean isEmpty();
/** Return the index of the last matching element in this list
* Return -1 if no match. */
public int lastIndexOf(E e);
/** Remove the first occurrence of the element o from this list.
* Shift any subsequent elements to the left.
* Return true if the element is removed. */
public boolean remove(E e);
/** Remove the element at the specified position in this list
* Shift any subsequent elements to the left.
* Return the element that was removed from the list. */
public E remove(int index);
/** Replace the element at the specified position in this list
* with the specified element and returns the new set. */
public Object set(int index, E e);
/** Return the number of elements in this list */
public int size();
}
Output:
Linked List Elements : [AAAAA, 1, 2, 3, ZZZZZ]
First element: AAAAA
Second element: ZZZZZ
Removed First Element: AAAAA
Now Linked List Elements : [1, 2, 3, ZZZZZ]
Removed Last Element: ZZZZZ
Now Linked List Elements : [1, 2, 3]
Removed all element:
Now Linked List Elements : []

More Related Content

Similar to Hi,I have added the methods and main class as per your requirement.pdf

we using java code DynamicArrayjava Replace all .pdf
we using java code   DynamicArrayjava   Replace all .pdfwe using java code   DynamicArrayjava   Replace all .pdf
we using java code DynamicArrayjava Replace all .pdfgudduraza28
 
please read below it will tell you what we are using L.pdf
please read below it will tell you what we are using   L.pdfplease read below it will tell you what we are using   L.pdf
please read below it will tell you what we are using L.pdfankit11134
 
please read the steps below and it will tell you what we usi.pdf
please read the steps below and it will tell you what we usi.pdfplease read the steps below and it will tell you what we usi.pdf
please read the steps below and it will tell you what we usi.pdfaggarwalopticalsco
 
ReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdfReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdfravikapoorindia
 
Implementation The starter code includes List.java. You should not c.pdf
Implementation The starter code includes List.java. You should not c.pdfImplementation The starter code includes List.java. You should not c.pdf
Implementation The starter code includes List.java. You should not c.pdfmaheshkumar12354
 
The LinkedList1 class implements a Linked list. class.pdf
The LinkedList1 class implements a Linked list. class.pdfThe LinkedList1 class implements a Linked list. class.pdf
The LinkedList1 class implements a Linked list. class.pdfmalavshah9013
 
package ADTs public interface CollectionADTltTgt .pdf
package ADTs public interface CollectionADTltTgt      .pdfpackage ADTs public interface CollectionADTltTgt      .pdf
package ADTs public interface CollectionADTltTgt .pdfsyedabdul78662
 
Implement the additional 5 methods as indicated in the LinkedList fi.pdf
Implement the additional 5 methods as indicated in the LinkedList fi.pdfImplement the additional 5 methods as indicated in the LinkedList fi.pdf
Implement the additional 5 methods as indicated in the LinkedList fi.pdffootstatus
 
The MyLinkedList class used in Listing 24.6 is a one-way directional .docx
 The MyLinkedList class used in Listing 24.6 is a one-way directional .docx The MyLinkedList class used in Listing 24.6 is a one-way directional .docx
The MyLinkedList class used in Listing 24.6 is a one-way directional .docxKomlin1
 
Please do parts labeled TODO LinkedList.java Replace.pdf
Please do parts labeled TODO LinkedList.java Replace.pdfPlease do parts labeled TODO LinkedList.java Replace.pdf
Please do parts labeled TODO LinkedList.java Replace.pdfaioils
 
we using java dynamicArray package modellinearpub imp.pdf
we using java dynamicArray    package modellinearpub   imp.pdfwe using java dynamicArray    package modellinearpub   imp.pdf
we using java dynamicArray package modellinearpub imp.pdfadityagupta3310
 
import java.util.Iterator; import java.util.NoSuchElementException; .pdf
  import java.util.Iterator; import java.util.NoSuchElementException; .pdf  import java.util.Iterator; import java.util.NoSuchElementException; .pdf
import java.util.Iterator; import java.util.NoSuchElementException; .pdfdeepakangel
 
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdf2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdfarshin9
 
For this lab you will complete the class MyArrayList by implementing.pdf
For this lab you will complete the class MyArrayList by implementing.pdfFor this lab you will complete the class MyArrayList by implementing.pdf
For this lab you will complete the class MyArrayList by implementing.pdffashiongallery1
 
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdf
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdfHere is the editable codeSolutionimport java.util.NoSuchEleme.pdf
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdfarrowmobile
 
Lecture 18Dynamic Data Structures and Generics (II).docx
Lecture 18Dynamic Data Structures and Generics (II).docxLecture 18Dynamic Data Structures and Generics (II).docx
Lecture 18Dynamic Data Structures and Generics (II).docxSHIVA101531
 
Java Foundations StackADT-java --- - Defines the interface to a stack.docx
Java Foundations StackADT-java ---  - Defines the interface to a stack.docxJava Foundations StackADT-java ---  - Defines the interface to a stack.docx
Java Foundations StackADT-java --- - Defines the interface to a stack.docxVictorXUQGloverl
 
JAVA Demonstrate the use of your APL in a PartB_Driver class by doing.docx
JAVA Demonstrate the use of your APL in a PartB_Driver class by doing.docxJAVA Demonstrate the use of your APL in a PartB_Driver class by doing.docx
JAVA Demonstrate the use of your APL in a PartB_Driver class by doing.docxGavinUJtMathist
 
Please help me to make a programming project I have to sue them today- (1).pdf
Please help me to make a programming project I have to sue them today- (1).pdfPlease help me to make a programming project I have to sue them today- (1).pdf
Please help me to make a programming project I have to sue them today- (1).pdfseoagam1
 
import java-util--- public class MyLinkedList{ public static void.pdf
import java-util---  public class MyLinkedList{    public static void.pdfimport java-util---  public class MyLinkedList{    public static void.pdf
import java-util--- public class MyLinkedList{ public static void.pdfasarudheen07
 

Similar to Hi,I have added the methods and main class as per your requirement.pdf (20)

we using java code DynamicArrayjava Replace all .pdf
we using java code   DynamicArrayjava   Replace all .pdfwe using java code   DynamicArrayjava   Replace all .pdf
we using java code DynamicArrayjava Replace all .pdf
 
please read below it will tell you what we are using L.pdf
please read below it will tell you what we are using   L.pdfplease read below it will tell you what we are using   L.pdf
please read below it will tell you what we are using L.pdf
 
please read the steps below and it will tell you what we usi.pdf
please read the steps below and it will tell you what we usi.pdfplease read the steps below and it will tell you what we usi.pdf
please read the steps below and it will tell you what we usi.pdf
 
ReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdfReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdf
 
Implementation The starter code includes List.java. You should not c.pdf
Implementation The starter code includes List.java. You should not c.pdfImplementation The starter code includes List.java. You should not c.pdf
Implementation The starter code includes List.java. You should not c.pdf
 
The LinkedList1 class implements a Linked list. class.pdf
The LinkedList1 class implements a Linked list. class.pdfThe LinkedList1 class implements a Linked list. class.pdf
The LinkedList1 class implements a Linked list. class.pdf
 
package ADTs public interface CollectionADTltTgt .pdf
package ADTs public interface CollectionADTltTgt      .pdfpackage ADTs public interface CollectionADTltTgt      .pdf
package ADTs public interface CollectionADTltTgt .pdf
 
Implement the additional 5 methods as indicated in the LinkedList fi.pdf
Implement the additional 5 methods as indicated in the LinkedList fi.pdfImplement the additional 5 methods as indicated in the LinkedList fi.pdf
Implement the additional 5 methods as indicated in the LinkedList fi.pdf
 
The MyLinkedList class used in Listing 24.6 is a one-way directional .docx
 The MyLinkedList class used in Listing 24.6 is a one-way directional .docx The MyLinkedList class used in Listing 24.6 is a one-way directional .docx
The MyLinkedList class used in Listing 24.6 is a one-way directional .docx
 
Please do parts labeled TODO LinkedList.java Replace.pdf
Please do parts labeled TODO LinkedList.java Replace.pdfPlease do parts labeled TODO LinkedList.java Replace.pdf
Please do parts labeled TODO LinkedList.java Replace.pdf
 
we using java dynamicArray package modellinearpub imp.pdf
we using java dynamicArray    package modellinearpub   imp.pdfwe using java dynamicArray    package modellinearpub   imp.pdf
we using java dynamicArray package modellinearpub imp.pdf
 
import java.util.Iterator; import java.util.NoSuchElementException; .pdf
  import java.util.Iterator; import java.util.NoSuchElementException; .pdf  import java.util.Iterator; import java.util.NoSuchElementException; .pdf
import java.util.Iterator; import java.util.NoSuchElementException; .pdf
 
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdf2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
 
For this lab you will complete the class MyArrayList by implementing.pdf
For this lab you will complete the class MyArrayList by implementing.pdfFor this lab you will complete the class MyArrayList by implementing.pdf
For this lab you will complete the class MyArrayList by implementing.pdf
 
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdf
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdfHere is the editable codeSolutionimport java.util.NoSuchEleme.pdf
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdf
 
Lecture 18Dynamic Data Structures and Generics (II).docx
Lecture 18Dynamic Data Structures and Generics (II).docxLecture 18Dynamic Data Structures and Generics (II).docx
Lecture 18Dynamic Data Structures and Generics (II).docx
 
Java Foundations StackADT-java --- - Defines the interface to a stack.docx
Java Foundations StackADT-java ---  - Defines the interface to a stack.docxJava Foundations StackADT-java ---  - Defines the interface to a stack.docx
Java Foundations StackADT-java --- - Defines the interface to a stack.docx
 
JAVA Demonstrate the use of your APL in a PartB_Driver class by doing.docx
JAVA Demonstrate the use of your APL in a PartB_Driver class by doing.docxJAVA Demonstrate the use of your APL in a PartB_Driver class by doing.docx
JAVA Demonstrate the use of your APL in a PartB_Driver class by doing.docx
 
Please help me to make a programming project I have to sue them today- (1).pdf
Please help me to make a programming project I have to sue them today- (1).pdfPlease help me to make a programming project I have to sue them today- (1).pdf
Please help me to make a programming project I have to sue them today- (1).pdf
 
import java-util--- public class MyLinkedList{ public static void.pdf
import java-util---  public class MyLinkedList{    public static void.pdfimport java-util---  public class MyLinkedList{    public static void.pdf
import java-util--- public class MyLinkedList{ public static void.pdf
 

More from annaelctronics

two singals are expected. one is for CH3, the oth.pdf
                     two singals are expected. one is for CH3, the oth.pdf                     two singals are expected. one is for CH3, the oth.pdf
two singals are expected. one is for CH3, the oth.pdfannaelctronics
 
There is in fact a stronger problem, namely 2p C .pdf
                     There is in fact a stronger problem, namely 2p C .pdf                     There is in fact a stronger problem, namely 2p C .pdf
There is in fact a stronger problem, namely 2p C .pdfannaelctronics
 
The term Lewis acid refers to a definition of aci.pdf
                     The term Lewis acid refers to a definition of aci.pdf                     The term Lewis acid refers to a definition of aci.pdf
The term Lewis acid refers to a definition of aci.pdfannaelctronics
 
NHC(=O)CH3 NH2 OH .pdf
                     NHC(=O)CH3    NH2    OH                        .pdf                     NHC(=O)CH3    NH2    OH                        .pdf
NHC(=O)CH3 NH2 OH .pdfannaelctronics
 
MnO2 may act as a catalyst.in the other reaction .pdf
                     MnO2 may act as a catalyst.in the other reaction .pdf                     MnO2 may act as a catalyst.in the other reaction .pdf
MnO2 may act as a catalyst.in the other reaction .pdfannaelctronics
 
What are P and R hereSolutionWhat are P and R here.pdf
What are P and R hereSolutionWhat are P and R here.pdfWhat are P and R hereSolutionWhat are P and R here.pdf
What are P and R hereSolutionWhat are P and R here.pdfannaelctronics
 
Intermolecular attractions are attractions betwee.pdf
                     Intermolecular attractions are attractions betwee.pdf                     Intermolecular attractions are attractions betwee.pdf
Intermolecular attractions are attractions betwee.pdfannaelctronics
 
It is insoluble in water. .pdf
                     It is insoluble in water.                        .pdf                     It is insoluble in water.                        .pdf
It is insoluble in water. .pdfannaelctronics
 
Write it using the ^ symbol. For example 1.34 10^6Solutio.pdf
Write it using the ^ symbol. For example 1.34  10^6Solutio.pdfWrite it using the ^ symbol. For example 1.34  10^6Solutio.pdf
Write it using the ^ symbol. For example 1.34 10^6Solutio.pdfannaelctronics
 
Xenodiagnosis is the method used to document presesnce of a microorg.pdf
Xenodiagnosis is the method used to document presesnce of a microorg.pdfXenodiagnosis is the method used to document presesnce of a microorg.pdf
Xenodiagnosis is the method used to document presesnce of a microorg.pdfannaelctronics
 
u(x)= ( -4x)Solutionu(x)= ( -4x).pdf
u(x)= ( -4x)Solutionu(x)= ( -4x).pdfu(x)= ( -4x)Solutionu(x)= ( -4x).pdf
u(x)= ( -4x)Solutionu(x)= ( -4x).pdfannaelctronics
 
There are many more conditions than just the norms of the culture th.pdf
There are many more conditions than just the norms of the culture th.pdfThere are many more conditions than just the norms of the culture th.pdf
There are many more conditions than just the norms of the culture th.pdfannaelctronics
 
The three layers of smooth muscle that includes mucosa. innermost tu.pdf
The three layers of smooth muscle that includes mucosa. innermost tu.pdfThe three layers of smooth muscle that includes mucosa. innermost tu.pdf
The three layers of smooth muscle that includes mucosa. innermost tu.pdfannaelctronics
 
The independent variable is the one which changes in each plant. Thi.pdf
The independent variable is the one which changes in each plant. Thi.pdfThe independent variable is the one which changes in each plant. Thi.pdf
The independent variable is the one which changes in each plant. Thi.pdfannaelctronics
 
Species diversity is more in near island as rate of immigration is m.pdf
Species diversity is more in near island as rate of immigration is m.pdfSpecies diversity is more in near island as rate of immigration is m.pdf
Species diversity is more in near island as rate of immigration is m.pdfannaelctronics
 
Solution Flies do not have teeth for chewing food.So,like human f.pdf
Solution Flies do not have teeth for chewing food.So,like human f.pdfSolution Flies do not have teeth for chewing food.So,like human f.pdf
Solution Flies do not have teeth for chewing food.So,like human f.pdfannaelctronics
 
Program To change this license header, choose License Heade.pdf
Program  To change this license header, choose License Heade.pdfProgram  To change this license header, choose License Heade.pdf
Program To change this license header, choose License Heade.pdfannaelctronics
 
plexusFormed from anterioe rani o these spinal nervesMajor nerve.pdf
plexusFormed from anterioe rani o these spinal nervesMajor nerve.pdfplexusFormed from anterioe rani o these spinal nervesMajor nerve.pdf
plexusFormed from anterioe rani o these spinal nervesMajor nerve.pdfannaelctronics
 
Ok, so the number of double bond equivalents in the compound is [C4H.pdf
Ok, so the number of double bond equivalents in the compound is [C4H.pdfOk, so the number of double bond equivalents in the compound is [C4H.pdf
Ok, so the number of double bond equivalents in the compound is [C4H.pdfannaelctronics
 
order of overlap of atomic orbitals from highest extent of overlap t.pdf
order of overlap of atomic orbitals from highest extent of overlap t.pdforder of overlap of atomic orbitals from highest extent of overlap t.pdf
order of overlap of atomic orbitals from highest extent of overlap t.pdfannaelctronics
 

More from annaelctronics (20)

two singals are expected. one is for CH3, the oth.pdf
                     two singals are expected. one is for CH3, the oth.pdf                     two singals are expected. one is for CH3, the oth.pdf
two singals are expected. one is for CH3, the oth.pdf
 
There is in fact a stronger problem, namely 2p C .pdf
                     There is in fact a stronger problem, namely 2p C .pdf                     There is in fact a stronger problem, namely 2p C .pdf
There is in fact a stronger problem, namely 2p C .pdf
 
The term Lewis acid refers to a definition of aci.pdf
                     The term Lewis acid refers to a definition of aci.pdf                     The term Lewis acid refers to a definition of aci.pdf
The term Lewis acid refers to a definition of aci.pdf
 
NHC(=O)CH3 NH2 OH .pdf
                     NHC(=O)CH3    NH2    OH                        .pdf                     NHC(=O)CH3    NH2    OH                        .pdf
NHC(=O)CH3 NH2 OH .pdf
 
MnO2 may act as a catalyst.in the other reaction .pdf
                     MnO2 may act as a catalyst.in the other reaction .pdf                     MnO2 may act as a catalyst.in the other reaction .pdf
MnO2 may act as a catalyst.in the other reaction .pdf
 
What are P and R hereSolutionWhat are P and R here.pdf
What are P and R hereSolutionWhat are P and R here.pdfWhat are P and R hereSolutionWhat are P and R here.pdf
What are P and R hereSolutionWhat are P and R here.pdf
 
Intermolecular attractions are attractions betwee.pdf
                     Intermolecular attractions are attractions betwee.pdf                     Intermolecular attractions are attractions betwee.pdf
Intermolecular attractions are attractions betwee.pdf
 
It is insoluble in water. .pdf
                     It is insoluble in water.                        .pdf                     It is insoluble in water.                        .pdf
It is insoluble in water. .pdf
 
Write it using the ^ symbol. For example 1.34 10^6Solutio.pdf
Write it using the ^ symbol. For example 1.34  10^6Solutio.pdfWrite it using the ^ symbol. For example 1.34  10^6Solutio.pdf
Write it using the ^ symbol. For example 1.34 10^6Solutio.pdf
 
Xenodiagnosis is the method used to document presesnce of a microorg.pdf
Xenodiagnosis is the method used to document presesnce of a microorg.pdfXenodiagnosis is the method used to document presesnce of a microorg.pdf
Xenodiagnosis is the method used to document presesnce of a microorg.pdf
 
u(x)= ( -4x)Solutionu(x)= ( -4x).pdf
u(x)= ( -4x)Solutionu(x)= ( -4x).pdfu(x)= ( -4x)Solutionu(x)= ( -4x).pdf
u(x)= ( -4x)Solutionu(x)= ( -4x).pdf
 
There are many more conditions than just the norms of the culture th.pdf
There are many more conditions than just the norms of the culture th.pdfThere are many more conditions than just the norms of the culture th.pdf
There are many more conditions than just the norms of the culture th.pdf
 
The three layers of smooth muscle that includes mucosa. innermost tu.pdf
The three layers of smooth muscle that includes mucosa. innermost tu.pdfThe three layers of smooth muscle that includes mucosa. innermost tu.pdf
The three layers of smooth muscle that includes mucosa. innermost tu.pdf
 
The independent variable is the one which changes in each plant. Thi.pdf
The independent variable is the one which changes in each plant. Thi.pdfThe independent variable is the one which changes in each plant. Thi.pdf
The independent variable is the one which changes in each plant. Thi.pdf
 
Species diversity is more in near island as rate of immigration is m.pdf
Species diversity is more in near island as rate of immigration is m.pdfSpecies diversity is more in near island as rate of immigration is m.pdf
Species diversity is more in near island as rate of immigration is m.pdf
 
Solution Flies do not have teeth for chewing food.So,like human f.pdf
Solution Flies do not have teeth for chewing food.So,like human f.pdfSolution Flies do not have teeth for chewing food.So,like human f.pdf
Solution Flies do not have teeth for chewing food.So,like human f.pdf
 
Program To change this license header, choose License Heade.pdf
Program  To change this license header, choose License Heade.pdfProgram  To change this license header, choose License Heade.pdf
Program To change this license header, choose License Heade.pdf
 
plexusFormed from anterioe rani o these spinal nervesMajor nerve.pdf
plexusFormed from anterioe rani o these spinal nervesMajor nerve.pdfplexusFormed from anterioe rani o these spinal nervesMajor nerve.pdf
plexusFormed from anterioe rani o these spinal nervesMajor nerve.pdf
 
Ok, so the number of double bond equivalents in the compound is [C4H.pdf
Ok, so the number of double bond equivalents in the compound is [C4H.pdfOk, so the number of double bond equivalents in the compound is [C4H.pdf
Ok, so the number of double bond equivalents in the compound is [C4H.pdf
 
order of overlap of atomic orbitals from highest extent of overlap t.pdf
order of overlap of atomic orbitals from highest extent of overlap t.pdforder of overlap of atomic orbitals from highest extent of overlap t.pdf
order of overlap of atomic orbitals from highest extent of overlap t.pdf
 

Recently uploaded

Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 

Recently uploaded (20)

Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 

Hi,I have added the methods and main class as per your requirement.pdf

  • 1. Hi, I have added the methods and main class as per your requirement. it is working fine now. Highlighted the code changes. MyLinkedListTest.java public class MyLinkedListTest { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub MyLinkedList list = new MyLinkedList(); list.addFirst("AAAAA"); list.add("1"); list.add("2"); list.add("3"); list.addLast("ZZZZZ"); System.out.println("Linked List Elements : "+list.toString()); System.out.println("First element: "+list.getFirst()); System.out.println("Second element: "+list.getLast()); System.out.println("Removed First Element: "+list.removeFirst()); System.out.println("Now Linked List Elements : "+list.toString()); System.out.println("Removed Last Element: "+list.removeLast()); System.out.println("Now Linked List Elements : "+list.toString()); System.out.println("Removed all element: "); list.removeAll(); System.out.println("Now Linked List Elements : "+list.toString()); } } MyLinkedList.java public class MyLinkedList extends MyAbstractList { private Node head, tail; /** Create a default list */ public MyLinkedList() {
  • 2. } /** Create a list from an array of objects */ public MyLinkedList(E[] objects) { super(objects); } /** Return the head element in the list */ public E getFirst() { if (size == 0) { return null; } else { return (E)head.element; } } /** Return the last element in the list */ public E getLast() { if (size == 0) { return null; } else { return (E)tail.element; } } /** Add an element to the beginning of the list */ public void addFirst(E e) { Node newNode = new Node(e); // Create a new node newNode.next = head; // link the new node with the head head = newNode; // head points to the new node size++; // Increase list size if (tail == null) // the new node is the only node in list tail = head; } /** Add an element to the end of the list */ public void addLast(E e) { Node newNode = new Node(e); // Create a new for element e if (tail == null) {
  • 3. head = tail = newNode; // The new node is the only node in list } else { tail.next = newNode; // Link the new with the last node tail = tail.next; // tail now points to the last node } size++; // Increase size } /** Add a new element at the specified index in this list * The index of the head element is 0 */ public void add(int index, E e) { if (index == 0) { addFirst(e); } else if (index >= size) { addLast(e); } else { Node current = head; for (int i = 1; i < index; i++) { current = current.next; } Node temp = current.next; current.next = new Node(e); (current.next).next = temp; size++; } } /** Remove the head node and * return the object that is contained in the removed node. */ public E removeFirst() { if (size == 0) { return null; } else {
  • 4. Node temp = head; head = head.next; size--; if (head == null) { tail = null; } return (E)temp.element; } } /** Remove all elements from list */ public void removeAll() { while(true) { if (size == 0) { break; } else { Node temp = head; head = head.next; size--; if (head == null) { tail = null; } } } } /** Remove the last node and * return the object that is contained in the removed node. */ public E removeLast() { if (size == 0) { return null; } else if (size == 1) { Node temp = head; head = tail = null; size = 0;
  • 5. return (E)temp.element; } else { Node current = head; for (int i = 0; i < size - 2; i++) { current = current.next; } Node temp = tail; tail = current; tail.next = null; size--; return (E)temp.element; } } /** Remove the element at the specified position in this list. * Return the element that was removed from the list. */ public E remove(int index) { if (index < 0 || index >= size) { return null; } else if (index == 0) { return removeFirst(); } else if (index == size - 1) { return removeLast(); } else { Node previous = head; for (int i = 1; i < index; i++) { previous = previous.next; } Node current = previous.next; previous.next = current.next; size--; return (E)current.element; }
  • 6. } /** Override toString() to return elements in the list */ public String toString() { StringBuilder result = new StringBuilder("["); Node current = head; for (int i = 0; i < size; i++) { result.append(current.element); current = current.next; if (current != null) { result.append(", "); // Separate two elements with a comma } } result.append("]"); // Insert the closing ] in the string return result.toString(); } /** Clear the list */ public void clear() { head = tail = null; } /** Return true if this list contains the element o */ public boolean contains(E e) { System.out.println("Implementation left as an exercise"); return true; } /** Return the element from this list at the specified index */ public E get(int index) { System.out.println("Implementation left as an exercise"); return null; } /** Return the index of the head matching element in this list. * Return -1 if no match. */ public int indexOf(E e) { System.out.println("Implementation left as an exercise"); return 0;
  • 7. } /** Return the index of the last matching element in this list * Return -1 if no match. */ public int lastIndexOf(E e) { System.out.println("Implementation left as an exercise"); return 0; } /** Replace the element at the specified position in this list * with the specified element. */ public E set(int index, E e) { System.out.println("Implementation left as an exercise"); return null; } private static class Node { E element; Node next; public Node(E element) { this.element = element; } } } MyAbstractList.java public abstract class MyAbstractList implements MyList { protected int size = 0; // The size of the list /** Create a default list */ protected MyAbstractList() { } /** Create a list from an array of objects */ protected MyAbstractList(E[] objects) { for (int i = 0; i < objects.length; i++) add(objects[i]); } /** Add a new element at the end of this list */ public void add(E e) { add(size, e);
  • 8. } /** Return true if this list contains no elements */ public boolean isEmpty() { return size == 0; } /** Return the number of elements in this list */ public int size() { return size; } /** Remove the first occurrence of the element o from this list. * Shift any subsequent elements to the left. * Return true if the element is removed. */ public boolean remove(E e) { if (indexOf(e) >= 0) { remove(indexOf(e)); return true; } else return false; } } MyList.java public interface MyList { /** Add a new element at the end of this list */ public void add(E e); /** Add a new element at the specified index in this list */ public void add(int index, E e); /** Clear the list */ public void clear(); /** Return true if this list contains the element */ public boolean contains(E e); /** Return the element from this list at the specified index */ public E get(int index); /** Return the index of the first matching element in this list. * Return -1 if no match. */
  • 9. public int indexOf(E e); /** Return true if this list contains no elements */ public boolean isEmpty(); /** Return the index of the last matching element in this list * Return -1 if no match. */ public int lastIndexOf(E e); /** Remove the first occurrence of the element o from this list. * Shift any subsequent elements to the left. * Return true if the element is removed. */ public boolean remove(E e); /** Remove the element at the specified position in this list * Shift any subsequent elements to the left. * Return the element that was removed from the list. */ public E remove(int index); /** Replace the element at the specified position in this list * with the specified element and returns the new set. */ public Object set(int index, E e); /** Return the number of elements in this list */ public int size(); } Output: Linked List Elements : [AAAAA, 1, 2, 3, ZZZZZ] First element: AAAAA Second element: ZZZZZ Removed First Element: AAAAA Now Linked List Elements : [1, 2, 3, ZZZZZ] Removed Last Element: ZZZZZ Now Linked List Elements : [1, 2, 3] Removed all element: Now Linked List Elements : [] Solution Hi, I have added the methods and main class as per your requirement. it is working fine now. Highlighted the code changes.
  • 10. MyLinkedListTest.java public class MyLinkedListTest { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub MyLinkedList list = new MyLinkedList(); list.addFirst("AAAAA"); list.add("1"); list.add("2"); list.add("3"); list.addLast("ZZZZZ"); System.out.println("Linked List Elements : "+list.toString()); System.out.println("First element: "+list.getFirst()); System.out.println("Second element: "+list.getLast()); System.out.println("Removed First Element: "+list.removeFirst()); System.out.println("Now Linked List Elements : "+list.toString()); System.out.println("Removed Last Element: "+list.removeLast()); System.out.println("Now Linked List Elements : "+list.toString()); System.out.println("Removed all element: "); list.removeAll(); System.out.println("Now Linked List Elements : "+list.toString()); } } MyLinkedList.java public class MyLinkedList extends MyAbstractList { private Node head, tail; /** Create a default list */ public MyLinkedList() { } /** Create a list from an array of objects */ public MyLinkedList(E[] objects) { super(objects);
  • 11. } /** Return the head element in the list */ public E getFirst() { if (size == 0) { return null; } else { return (E)head.element; } } /** Return the last element in the list */ public E getLast() { if (size == 0) { return null; } else { return (E)tail.element; } } /** Add an element to the beginning of the list */ public void addFirst(E e) { Node newNode = new Node(e); // Create a new node newNode.next = head; // link the new node with the head head = newNode; // head points to the new node size++; // Increase list size if (tail == null) // the new node is the only node in list tail = head; } /** Add an element to the end of the list */ public void addLast(E e) { Node newNode = new Node(e); // Create a new for element e if (tail == null) { head = tail = newNode; // The new node is the only node in list } else { tail.next = newNode; // Link the new with the last node
  • 12. tail = tail.next; // tail now points to the last node } size++; // Increase size } /** Add a new element at the specified index in this list * The index of the head element is 0 */ public void add(int index, E e) { if (index == 0) { addFirst(e); } else if (index >= size) { addLast(e); } else { Node current = head; for (int i = 1; i < index; i++) { current = current.next; } Node temp = current.next; current.next = new Node(e); (current.next).next = temp; size++; } } /** Remove the head node and * return the object that is contained in the removed node. */ public E removeFirst() { if (size == 0) { return null; } else { Node temp = head; head = head.next; size--; if (head == null) {
  • 13. tail = null; } return (E)temp.element; } } /** Remove all elements from list */ public void removeAll() { while(true) { if (size == 0) { break; } else { Node temp = head; head = head.next; size--; if (head == null) { tail = null; } } } } /** Remove the last node and * return the object that is contained in the removed node. */ public E removeLast() { if (size == 0) { return null; } else if (size == 1) { Node temp = head; head = tail = null; size = 0; return (E)temp.element; } else { Node current = head;
  • 14. for (int i = 0; i < size - 2; i++) { current = current.next; } Node temp = tail; tail = current; tail.next = null; size--; return (E)temp.element; } } /** Remove the element at the specified position in this list. * Return the element that was removed from the list. */ public E remove(int index) { if (index < 0 || index >= size) { return null; } else if (index == 0) { return removeFirst(); } else if (index == size - 1) { return removeLast(); } else { Node previous = head; for (int i = 1; i < index; i++) { previous = previous.next; } Node current = previous.next; previous.next = current.next; size--; return (E)current.element; } } /** Override toString() to return elements in the list */ public String toString() { StringBuilder result = new StringBuilder("[");
  • 15. Node current = head; for (int i = 0; i < size; i++) { result.append(current.element); current = current.next; if (current != null) { result.append(", "); // Separate two elements with a comma } } result.append("]"); // Insert the closing ] in the string return result.toString(); } /** Clear the list */ public void clear() { head = tail = null; } /** Return true if this list contains the element o */ public boolean contains(E e) { System.out.println("Implementation left as an exercise"); return true; } /** Return the element from this list at the specified index */ public E get(int index) { System.out.println("Implementation left as an exercise"); return null; } /** Return the index of the head matching element in this list. * Return -1 if no match. */ public int indexOf(E e) { System.out.println("Implementation left as an exercise"); return 0; } /** Return the index of the last matching element in this list * Return -1 if no match. */ public int lastIndexOf(E e) {
  • 16. System.out.println("Implementation left as an exercise"); return 0; } /** Replace the element at the specified position in this list * with the specified element. */ public E set(int index, E e) { System.out.println("Implementation left as an exercise"); return null; } private static class Node { E element; Node next; public Node(E element) { this.element = element; } } } MyAbstractList.java public abstract class MyAbstractList implements MyList { protected int size = 0; // The size of the list /** Create a default list */ protected MyAbstractList() { } /** Create a list from an array of objects */ protected MyAbstractList(E[] objects) { for (int i = 0; i < objects.length; i++) add(objects[i]); } /** Add a new element at the end of this list */ public void add(E e) { add(size, e); } /** Return true if this list contains no elements */ public boolean isEmpty() { return size == 0;
  • 17. } /** Return the number of elements in this list */ public int size() { return size; } /** Remove the first occurrence of the element o from this list. * Shift any subsequent elements to the left. * Return true if the element is removed. */ public boolean remove(E e) { if (indexOf(e) >= 0) { remove(indexOf(e)); return true; } else return false; } } MyList.java public interface MyList { /** Add a new element at the end of this list */ public void add(E e); /** Add a new element at the specified index in this list */ public void add(int index, E e); /** Clear the list */ public void clear(); /** Return true if this list contains the element */ public boolean contains(E e); /** Return the element from this list at the specified index */ public E get(int index); /** Return the index of the first matching element in this list. * Return -1 if no match. */ public int indexOf(E e); /** Return true if this list contains no elements */ public boolean isEmpty(); /** Return the index of the last matching element in this list
  • 18. * Return -1 if no match. */ public int lastIndexOf(E e); /** Remove the first occurrence of the element o from this list. * Shift any subsequent elements to the left. * Return true if the element is removed. */ public boolean remove(E e); /** Remove the element at the specified position in this list * Shift any subsequent elements to the left. * Return the element that was removed from the list. */ public E remove(int index); /** Replace the element at the specified position in this list * with the specified element and returns the new set. */ public Object set(int index, E e); /** Return the number of elements in this list */ public int size(); } Output: Linked List Elements : [AAAAA, 1, 2, 3, ZZZZZ] First element: AAAAA Second element: ZZZZZ Removed First Element: AAAAA Now Linked List Elements : [1, 2, 3, ZZZZZ] Removed Last Element: ZZZZZ Now Linked List Elements : [1, 2, 3] Removed all element: Now Linked List Elements : []