Two Exercises that need to be completed using JAva: package hw0; public class Li
ID: 665748 • Letter: T
Question
Two Exercises that need to be completed using JAva: package hw0; public class LinkedList { public final int value; public LinkedList next; public LinkedList (int value, LinkedList next) { this.value = value; this.next = next; } // EXERCISE 1: create a LinkedList that contains the three integers 1,2,3 (in that order). // You should hardcode that LinkedList! public static LinkedList testing123 () { //add code here } // EXERCISE 2: calculate the size of the LinkedList. You can use recursion or a while loop. public int size () { //add code here } public String toString () { return "LinkedList (" + value + ", " + (next == null ? "null" : next.toString ()) + ")"; } }
Explanation / Answer
class LinkedList {
public final int value;
public LinkedList next;
public LinkedList (int value, LinkedList next) {
this.value = value;
this.next = next;
}
// EXERCISE 1: create a LinkedList that contains the three integers 1,2,3 (in that order).
// You should hardcode that LinkedList!
public static LinkedList testing123 () {
LinkedList head=null;
LinkedList node1=new LinkedList(1,null);
LinkedList node2=new LinkedList(2,null);
LinkedList node3=new LinkedList(3,null);
head=node1;
node1.next=node2;
node2.next=node3;
return head;
}
// EXERCISE 2: calculate the size of the LinkedList. You can use recursion or a while loop.
public int size (LinkedList head) {
LinkedList t=head;
int size=0;
while(t!=null)
{
t=t.next;
size++;
}
return size;
}
public String toString () {
return "LinkedList (" + value + ", " + (next == null ? "null" : next.toString ()) + ")";
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.