Question: Write a non-member method named listReplacer() that receives as parameter a SinglyLinkedList L, and two elements e and f. The method replaces each copy of
Write a non-member method named listReplacer() that receives as parameter a SinglyLinkedListL, and two elements e and f.
The method replaces each copy of e with f in the list in time O(n)(), where n = L.size().
Solutions that are not O(n)() will get at most 50% of the score.
If e is not found, then the method returns a list that has the same elements as L. Notice that this method modifies L!
For example, if L = {Bob, Apu, Ned, Joe, Apu}, then a call to listReplacer(L, Apu, Kim ) produces {Bob, Kim, Ned, Joe, Kim}. Hint: Use an auxilary list to help you out, take advantage of the fact that Linked Lists have O(1)(1) time when adding, removing and inspecting at position 0 because all it does is it modifies or inspects header.getNext()
import java.util.Iterator; import java.util.NoSuchElementException;
public class LinkedListWrapper { public static interface List
public void add(E e); public void add(E e, int index); public E get(int index); public E remove(int index); public boolean remove(E e); public int removeAll(E e); public E replace(int index, E newElement); public void clear(); public Object[] toArray(); public void addAfter(E e, E f);
} public static class SinglyLinkedList
@SuppressWarnings("hiding") private class SinglyLinkedListIterator
@SuppressWarnings("unchecked") public SinglyLinkedListIterator() { this.nextNode = (Node
@Override public E next() { if (this.hasNext()) { E result = this.nextNode.getElement(); this.nextNode = this.nextNode.getNext(); return result; } else { throw new NoSuchElementException(); } } } private static class Node
}
private Node
@Override public boolean isEmpty() { return this.size() == 0; }
@Override public boolean isMember(E e) { return this.firstIndexOf(e) >= 0; }
@Override public int firstIndexOf(E e) { int i = 0; for (Node
@Override public void add(E e) { if (this.isEmpty()) { this.header.setNext(new Node
@Override public void add(E e, int index) { if ((index < 0) || (index > this.currentSize)) { throw new IndexOutOfBoundsException(); } if (index == this.currentSize) { this.add(e); } else { Node
@Override public E get(int position) { if ((position < 0) || position >= this.currentSize) { throw new IndexOutOfBoundsException(); } Node
}
@Override public int removeAll(E e) { int count = 0; while (this.remove(e)) { count++; } return count; }
@Override public void addAfter(E e, E f) { // ADD YOUR CODE HERE }
} }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
