java - EmptyStackException when trying to implement Comparator -
i'm new here , have problem. i'm trying implement comparator compare 2 stacks top. code looks this
class comp implements comparator<stack<integer>> { @override public int compare(stack<integer> st1,stack <integer> st2) { return st1.peek()-st2.peek(); } }
i got java.util.emptystackexception
@ st1.peek()-st2.peek();
, don't know why. maybe me better implementation problem. thanks!
stack.peek
throws emptystackexception
when stack empty. need check if stack empty before calling peek
on it, example, if want empty stacks come before non-empty ones:
@override public int compare(stack<integer> st1, stack<integer> st2) { if (st1.isempty() && st2.isempty()) { return 0; } if (st1.isempty()) { return -1; } if (st2.isempty()) { return 1; } return st1.peek() - st2.peek(); }
or if want empty stacks come after non-empty ones:
@override public int compare(stack<integer> st1, stack<integer> st2) { if (st1.isempty() && st2.isempty()) { return 0; } if (st1.isempty()) { return 1; } if (st2.isempty()) { return -1; } return st1.peek() - st2.peek(); }
Comments
Post a Comment