Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

Java 

Need help with stacks in Java

I need help with stacks, how would I code these questions? Thanks in advance!

1. In class StackDemo, complete the method countEven that when passed a stack of integers, returns the number of even numbers. The stack must remain unchanged after the method finishes execution. Return null if the stack is empty.

4. In class StackDemo, complete the method alternateItems that when passed a stack of integers, returns a stack containing every alternate item, starting from the top item, from the passed stack. For example, if the stack passed is [6, 3, 1, 8] (where 8 is the top item), returns the stack [3, 8], and when the stack passed is [2, 6, 3, 1, 8], returns the stack [2, 3, 8].

5. Write a method that when passed an array of integers, returns the array reversed, using a stack
Start with 5th question, if you dont know where to start - look up how a stack works.
(May 31, 2016 09:05 AM)Maxiim Wrote:  Start with 5th question, if you dont know where to start - look up how a stack works.

my question is that how would I code for these questions.
You didn't even provide StackDemo, how do you expect us to do this problem?
(May 31, 2016 10:27 AM)Jire Wrote:  You didn't even provide StackDemo, how do you expect us to do this problem?

import java.util.Stack;

public class StackDemo {

public static void main(String[] args) {

}


public static int countEven(Stack<Integer> stk) {

}


public static Stack<Integer> alternateItems(Stack<Integer> stk) {
return null;
}
}
OP you've made no effort to try. There's no point in us handing you the code, you won't learn anything. Take a look at this and make an attempt.

1. Loop through the stack, if the current int is even, increment a counter. Return the counter.

2. Create a new stack. while the original stack is not empty, pop/push the old stack to the new, skipping every second value. Return the new stack.

3. Create a new stack. Loop from the end of the array to the start, pushing each value to your new stack. Return the new stack.


Possibly Related Threads...
Thread / Author Replies Views Last Post
[Java] by FailzorroMar 13, 2018 10:58 PM 3 236 Mar 13, 2018 10:58 PM
Last Post: Xoreaux
[Java] by c-_-mMar 19, 2017 02:36 PM 7 591 Mar 19, 2017 02:36 PM
Last Post: Stealth™
[Java] by President HolyFeb 8, 2014 11:48 AM 3 187 Feb 8, 2014 11:48 AM
Last Post: Knautschtabak