Monday, 15 March 2010

numbers - Return the higher element than the top of the Stack in Java -


The method nbGreaterThanFirst that gives the number of elements in my stacks, assuming that the element at the top of my stock is greater than or equal to the element That's the top 5 of the stack, and it has elements of 7, 3 and 9. It should be returned as 9 because it is more than all other elements in the stack. The algorithms move me fine but it does not work. Any suggestions? import java.util.Stack; Public Class Growth Stacks {Public Stable Entity nbGreaterThanFirst (Stack & Lt; Integer & gt; Mistake) {int firststack = myStack.peek (); // first for stack = 5 (int i = 0; i > gt; = first stack) {// if any element 5 Is more than firstStack = myStack.peek (); MyStack.pop (); }} First return stack; } Public static zero main (string [] args) {stack & lt; Integer & gt; S = new stack & lt; Integer & gt; (); S.push (1); S.push (3); S.push (7); S.push (5); Println (nbGreaterThanFirst); }}

In the loop, you are sticking the element only when the stack is & gt; = Your current first stack variable: As soon as you get lower value elements compared to your current first stack value, your algorithm does not allow to populate the element and you move on to the stack.

For stacks with element 5, 7, 3, 9 as soon as you kill "3", this will fail your position and no element from the stack will be popped up. In this way you will never reach the "9" element.

My suggestion is to move pop () from the condition. I pop each recurrence one time so that all the elements are checked.

  int stackSize = myStack.size (); For (Int i = 0; I  = FirstStack) {// If any element is more than 5 then first stack = MyStacks.pk ( ); } MyStack.pop (); }    

No comments:

Post a Comment