Question: Java, working with nodes I need help with grabSome , with code in the bolded text below. The bolded code doesn't handle the case if
Java, working with nodes
I need help with grabSome, with code in the bolded text below. The bolded code doesn't handle the case if cur is null, having trouble with how to exactly what should happen in this case
public void grabSome(ThingType new_thing, int count) { // if head is null construct a new node for head if (head==null) { head = new CollectorNode(new_thing,count,head); } // if the head is the item we are adding then add here // reduces iterating through the linked list else if (head.thing == new_thing) { head.count += count; } else { CollectorNode pre = null, cur = null; // start at the 2nd element // (because we already checked the head) pre = head; cur = head.next; // iterate through the elements in our list // and stop if we find it or hit the end while (cur != null && (new_thing != cur.thing)) { pre = cur; cur = cur.next; } //! --- Bug Section --- // if (cur.thing == new_thing) { cur.count += count; return; } // create the new node, hitching the current after it CollectorNode n = new CollectorNode(new_thing,count,cur); // insert by hitching it after previous pre.next = n; //! ---End of section--- // } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
