In: Computer Science
This is based on LinkedLists. Avneet Pandey, please do not answer this. Both your previous answers were wrong.
Please complete the methods max() and threshold(). I'd greatly appreciate it. There is a type mismatch in my first method and I dont know how to get around it. I've commented on the line with the type mismatch. Please write a correct method in the answer so I can compare it to my wrong method
public class Node {
public T info;
public Node link;
public Node(T i, Node l) {
info = i; link = l;
}
}
class LinkedList> {
protected Node head = null;
public LinkedList add(T el) {
head = new Node(el, head);
return this;
}
public void print() {
for(Node node = head; node!=null; node=node.link) {
System.out.print(node.info+" ");
}
System.out.println("");
}
public T maxValue() { // Note: Recursive methods not allowed, using
new key word not allowed, no iterators allowed
if (head == null) {
return null;
}
else {
Node temp = head;
if (temp.link == null) {
return temp.info;
}
else {
T max = temp.link; //type mismatch
if (temp.info.compareTo(max) > 0)
max = temp.info;
return max;
}
}
}
public void threshold(T thres) {//Note: Recursive methods not
allowed, using new key word not allowed, no iterators allowed
}
public static void main(String args[]) {
LinkedList list = new LinkedList();
System.out.println(list.maxValue()); // should be null
list.add(20).add(30).add(10);
System.out.println(list.maxValue()); // should be 30
list.threshold(40);
list.print(); // should print out all elements
list.threshold(30);
list.print(); // should print out 10 20
list.threshold(10);
list.print(); // should print nothing
}
}
For max function just one line needed to be changed:
public T maxValue() { // Note: Recursive methods not allowed, using new key word not allowed, no iterators allowed
if (head == null) {
return null;
}
else {
Node temp = head;
if (temp.link == null) {
return temp.info;
}
else {
Node max = temp.link; //type mismatch was because link of Node is of Node type only and you tried to assign it to T type
if (temp.info.compareTo(max) > 0)
max = temp.info;
return max;
}
}
}
For threshold function. Appropriate comments have been put to explain the code
public void threshold(T thres) {//Note: Recursive methods not allowed, using new key word not allowed, no iterators allowed
// if no elements in list
if(head == null)
return;
//to iterate through the list
Node prev = head;
Node cur = prev.link;
while(cur != null){
//when threshold value is reached
if(cur.info.compareTo(thres) >=0){
prev.link = cur.link; //Skip the current node
cur = cur.link;
}
}
// check if fist element is greater than threshold
if(head.info.compareTo(thres)>=0)
head = head.link;
}