if we have following List classes: public class LinkedList<T> { class ListNode {
ID: 3718200 • Letter: I
Question
if we have following List classes:
public class LinkedList<T> {
class ListNode {
protected T value;
protected ListNode next;
public ListNode(T val, ListNode nxt) {
value = val;
next = nxt;
}
public ListNode(T val) {
this(val, null);
}
public ListNode() {
this(null, null);
}
}
can you write the folowing methods in java:
1.Write a method for the LinkedList class called int indexOf(T val) which returns the integer index indicating the location of val in the list, or -1 if val is not in the list.
2. Write a method for the LinkedList class called boolean equals(LinkedList rhs) which checks for deep equality, i.e. checks if rhs and the receiving object store the same values in the same order.
3. Assume that the method described in Problem 3 does not exist. Write a method boolean equals(LinkedList lhs, LinkedList rhs) that uses two ListIterators to check for deep equality of lists lhs and rhs. This code should NOT be part of the ListIterator class.
4. Write a recursive method void printReverse(Node node) which prints the values in the list referenced by node in reverse. You may assume that node references a valid node in the list, i.e. not the dummy header node. HINT: this method should only be 3 or 4 lines long.
5. Write a method for the LinkedList class called boolean removeLast(T val) which removes the last occurrence of val from the list. The method should return true if it is successful.
6. Repeat the previous problem using a doubly linked list.
Explanation / Answer
public class LinkedList<T> {
ListNode head;
class ListNode {
protected T value;
protected ListNode next;
public ListNode(T val, ListNode nxt) {
value = val;
next = nxt;
}
public ListNode(T val) {
this(val, null);
}
public ListNode() {
this(null, null);
}
}
int indexOf(T val) {
ListNode curr = head;
int index = -1;
while(curr!=null){
if(curr.value.equals(val)){
++index;
return index;
}
}
return index;
}
boolean equals(LinkedList rhs){
ListNode curr1 = this.head;
ListNode curr2 = rhs.head;
if(curr1 ==null && curr2==null)
return true;
if(curr1 ==null || curr2==null)
return false;
while(curr1!=null && curr2!=null){
if(!curr1.value.equals(curr2.value))
return false;
curr1 = curr1.next;
curr2 = curr2.next;
}
if(curr1 !=null || curr2!=null)
return false;
return true;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.