import java.util.*; import java.util.LinkedList; public class BabyElephantWalk {
ID: 3695966 • Letter: I
Question
import java.util.*;
import java.util.LinkedList;
public class BabyElephantWalk {
public static void main(String[] args) {
// TODO Auto-generated method stub
ElephantList walk = new ElephantList();
walk.add (new Elephant("Charlie"));
walk.add (new Elephant("Donna"));
walk.add (new Elephant("Chilli"));
walk.add (new Elephant("Piper"));
walk.add (new Elephant("Ziva"));
walk.delete ("Charlie");
System.out.println (walk);
}
}
public class ElephantList {
private ElephantNode head;
private ElephantNode list;
public ElephantList()
{
list = null;
}//end ElephantList constructor
public void add(Elephant cat)
{
ElephantNode node = new ElephantNode(cat);
ElephantNode current;
if (list == null)
list = node;
else
{
current = list;
while (current.next != null)
current = current.next;
current.next = node;
}
}//end add
public void delete(Object x)
{
if (list.data.equals(x)) // <<= 'head' replaced with 'list'; == replaced with .equals
{
list = list.next; // <<= 'head' replaced with 'list'
}
else
{
ElephantNode temp = list; // <<= 'head' replaced with 'list'
while (temp.next != null)
{
if (temp.next.data.equals(x))
{
temp.next = temp.next.next;
break;
}
else
{
temp = temp.next;
}
}
}
}
public String toString ()
{
String result = "";
ElephantNode current = list;
while (current != null)
{
result += current.elephant + " ";
current = current.next;
}
return result;
}//end toString
private class ElephantNode
{
public Elephant elephant;
public ElephantNode next;
public Object data;
public ElephantNode(Elephant cat)
{
elephant = cat;
next = null;
data = null;
}//end ElephantNode constructor
}//ElephantNode
}//end ElephantList
Explanation / Answer
class BabyElephantWalk { public static void main(String[] args) { // TODO Auto-generated method stub ElephantList walk = new ElephantList(); walk.add (new Elephant("Charlie")); walk.add (new Elephant("Donna")); walk.add (new Elephant("Chilli")); walk.add (new Elephant("Piper")); walk.add (new Elephant("Ziva")); walk.delete ("Charlie"); System.out.println (walk); } } class Elephant { String name; public Elephant(String name) { this.name = name; } } class ElephantList { private ElephantNode head; private ElephantNode list; public ElephantList() { list = null; }//end ElephantList constructor public void add(Elephant cat) { ElephantNode node = new ElephantNode(cat); ElephantNode current; if (list == null) list = node; else { current = list; while (current.next != null) current = current.next; current.next = node; } }//end add public void delete(Object x) { if (list.data.equals(x)) //Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.