Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

. AT&T 2:39 PM 0 2. Assume that a singly linked list is implemented with a heade

ID: 3753909 • Letter: #

Question

. AT&T 2:39 PM 0 2. Assume that a singly linked list is implemented with a header node, but no tail node, and that it maintains only a reference to the header node. (a) Write a method in Java to add (boolean add(Object x)) a value x if it is not already contained in the linked list. (b) Write a method in Java to print (void print() the linked list. Note: You can use the following method contains(Object x): boolean contains (object x) Nodecobject pead.next while (p null) if (x.equals(p.data)) return true; else P -p.next return false;

Explanation / Answer

Below are your methods: -

(a)

boolean add(Object x ) {

if (contains(x))

return false;

else {

Node<Object> p = new Node<Object>(x);

p.next = head.next;

head.next = p;

theSize++;

}

return true;

}

(b)

void print() {

Node<Object> p = head.next;

while (p != null) {

System.out.print(p.data + " ");

p = p.next;

}

System.out.println();

}