标签云

微信群

扫码加入我们

WeChat QR Code


When pointer is larger than Max, previous Max becomes secondMax and pointer becomes new Max; Max.next and pointer.next are of no consequence. And at the end of it all, secondMax is the desired result.

2018年12月17日19分27秒

thanks for the reply, is this what you mean with max becoming second max and pointer becoming new max? if(Max.key.compareTo(pointer.key)<=0) { secondMax=Max; Max=pointer; } else { Max=secondMax; pointer=Max; } } return secondMax.key; }

2018年12月17日19分27秒

I led you slightly astray, it's a little more complicated. If pointer.key > secondMax.key AND also pointer.key > Max.key, then secondMax becomes old Max and Max becomes pointer; but if if pointer.key > secondMax only, secondMax becomes pointer and Max stays the same.

2018年12月17日19分27秒

when I use this code i am getting a null pointer exception if(first == null) return null; if(size()<=1) return null; Node secondMax=null; Node Max=first; for (Node pointer=first.next;pointer.next!=null;pointer=pointer.next) { if(pointer.key.compareTo(secondMax.key)>0 && pointer.key.compareTo(Max.key)>0) { secondMax=Max; Max=pointer; } else if(pointer.key.compareTo(secondMax.key)>0) { secondMax=pointer; } } return secondMax.key; }

2018年12月17日19分27秒

Well, in order for the algorithm to work, you can't avoid starting off with at least secondMax == null so your code needs to be prepared to deal with that. For example, instead of just if (secondMax.key.compareTo(pointer.key) <= 0)..., you'd write if (secondMax==null || secondMax.key.compareTo(pointer.key) <= 0)...

2018年12月16日19分27秒

that helps thanks so much

2018年12月17日19分27秒