In: Computer Science
Code in Java
Given the LinkedList class that is shown below
Add the following methods:
public class MyLinkedList { | |
private String name; | |
private MyLinkedList next; | |
public MyLinkedList(String n) { | |
this.name = n; | |
} | |
public void add(String n) { | |
MyLinkedList i = this; | |
while (i.next != null) { | |
i = i.next; | |
} | |
i.next = new MyLinkedList(n); | |
} | |
public int length() { | |
int ret_val = 1; | |
MyLinkedList i = this; | |
while (i.next != null) { | |
i = i.next; | |
ret_val++; | |
} | |
return ret_val; | |
} | |
public void print() { | |
// ???? | |
} | |
public MyLinkedList itemAt(int index) { | |
int counter = 1; | |
MyLinkedList i = this; | |
while (i.next != null && counter < index) { | |
i = i.next; | |
counter++; | |
} | |
return i; | |
} | |
public static void main(String[] args) { | |
MyLinkedList student_list = new MyLinkedList("12"); | |
student_list.add("7"); | |
student_list.add("20"); | |
student_list.add("40"); | |
student_list.add("9"); | |
System.out.println(student_list.length()); | |
System.out.println(student_list.itemAt(3)); | |
System.out.println(); | |
} | |
} |
Please find the answer for the above given question..
ANSWER :
OUTPUT :
CODE : I have highlighted the code below which i have added.
class MyLinkedList {
private MyLinkedList next;
private String name;
public MyLinkedList(String n) {
this.name = n;
}
public void add(String n) {
MyLinkedList i = this;
while (i.next != null) {
i = i.next;
}
i.next = new MyLinkedList(n);
}
public int length() {
int ret_val = 1;
MyLinkedList i = this;
while (i.next != null) {
i = i.next;
ret_val++;
}
return ret_val;
}
public MyLinkedList itemAt(int index) {
int counter = 1;
MyLinkedList i = this;
while (i.next != null && counter < index) {
i = i.next;
counter++;
}
return i;
}
public void print() {
int counter =0;
MyLinkedList i = this;
System.out.println("Index\tElement");
while(i.next != null){
System.out.println(Integer.toString(counter)+"\t\t"+i.name);
i= i.next;
counter++;
}
System.out.println(Integer.toString(counter)+"\t\t"+i.name);
}
public static void main(String[] args) {
MyLinkedList student_list = new MyLinkedList("12");
student_list.add("7");
student_list.add("20");
student_list.add("40");
student_list.add("9");
System.out.println(student_list.length());
System.out.println(student_list.itemAt(3).name);
System.out.println();
student_list.print();
}
}
Thanks..