![]() |
|
[Java] Need help with stacks in Java - Printable Version +- Hack Forums (https://hackforums.net) +-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444) +--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151) +---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118) +---- Thread: [Java] Need help with stacks in Java (/showthread.php?tid=5288506) |
Need help with stacks in Java - techgeek4877 - May 31, 2016 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 * - Maxiim - May 31, 2016 Start with 5th question, if you dont know where to start - look up how a stack works. * - techgeek4877 - May 31, 2016 (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. * - Jire - May 31, 2016 You didn't even provide StackDemo, how do you expect us to do this problem? * - techgeek4877 - May 31, 2016 (May 31, 2016 10:27 AM)J i r e 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; } } * - Cathal - May 31, 2016 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. |