Question: Implement a method addBefore for OurLinkedList. This method takes 2 values x and y as arguments. It searches the list for x and adds y

Implement a method addBefore for OurLinkedList. This method takes 2 values x and y as arguments. It searches the list for x and adds y to the list immediately before the first time that x appears. If x doesnt appear, the method does nothing

This is the given code

.Implement a method addBefore for OurLinkedList. This method takes 2 values x

1 2 public class OurLinkedLists T> { private Node head; 4 public class Node { public T value; public Node next; public Node(t value, Node next) { this.value = value; this.next = next; } } 6 7 8 9 10 11 12 13 14 151 16 17 18 19 200 21 22 public void addFront (T newItem) { Node newNode = new Node(newItem, head); head = newNode; } public int size() { Node curr = head; int count = 0; while(curr != null) { count++; curr = curr.next; return count; } public void add(T toAdd) { Node curr = head; if(curr == null) { //special case: adding to empty list addFront(toAdd); return; } 27 28 29 301 31 32 33 34 35 36 37 38 39 40 41 42 43 44e 45 46 47 48 49 50 51 52 53 54 while(curr.next != null) { //advance curr so it points at the last node curr = curr.next; } Node newNode = new Node(toAdd, null); curr.next= newNode; } public I get(int index) { Node curr = head; int count = 0; while(curr != null) { if(count == index) return curr.value; count++; curr = curr.next; } throw new IndexOutOfBoundsException(); }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!