标签云

微信群

扫码加入我们

WeChat QR Code

so im writing a function that will find the second largest key in an un-ordered symbol table using a linked list implementation, the code I have so far isnt working right and was wondering if someone had any tips thanks! public Key secondLargestKey () {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(Max.key.compareTo(pointer.key)<=0) { secondMax=Max; Max=pointer.next;}else { secondMax=Max.next; Max=pointer; }} return Max.key;}`Output:secondLargestKeyTest: CorrectStringAnswer: nullsecondLargestKeyTest: CorrectString A Answer: nullsecondLargestKeyTest: *Error*String AB Expected A Actual: BsecondLargestKeyTest: CorrectString ABC Actual: BsecondLargestKeyTest: CorrectString ABABABC Actual: BsecondLargestKeyTest: *Error*String ZAYBXC Expected Y Actual: Z


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

2019年06月19日04分26秒

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; }

2019年06月19日04分26秒

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.

2019年06月19日04分26秒

when I use this code i am getting a null pointer exceptionif(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; }

2019年06月19日04分26秒

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)...

2019年06月19日04分26秒

that helps thanks so much

2019年06月19日04分26秒