Contents
- 1 How will you partition the memory if two stacks implemented within a single array?
- 2 How do you implement a stack using an array in Java?
- 3 What should be the growing direction of two stacks while implementing them in a single array so as to reduce the overflow chances?
- 4 Can we implement 2 stacks in a single array?
How will you partition the memory if two stacks implemented within a single array?
A simple solution would be to divide the array into two halves and allocate each half to implement two stacks. In other words, for an array A of size n , the solution would allocate A[0, n/2] memory for the first stack and A[n/2+1, n-1] memory for the second stack.
How do you implement a stack using an array in Java?
How to Implement Stack in Java Using Array and Generics?
- push() Method adds element x to the stack.
- pop() Method removes the last element of the stack.
- top() Method returns the last element of the stack.
- empty() Method returns whether the stack is empty or not.
How do we implement two stacks using only one array our stack routines should not indicate an exception unless every slot in the array is used?
Our stack routines should not indicate an exception unless every slot in the array is used? Algorithm: Start with two indexes, one at the left end and other at the right end. The left index simulates the first stack and the right index simulates the second stack.
What should be the growing direction of two stacks while implementing them in a single array so as to reduce the overflow chances?
Solution: The idea is to have two Stacks growing in opposite direction (toward each other). The first Stack (top1) will grow in forward direction and second stack (top2) will grow in the backward direction. to indicate that the two stacks are empty.
Can we implement 2 stacks in a single array?
A simple way to implement two stacks is to divide the array in two halves and assign the half half space to two stacks, i.e., use arr[0] to arr[n/2] for stack1, and arr[(n/2) + 1] to arr[n-1] for stack2 where arr[] is the array to be used to implement two stacks and size of array be n.
Is it possible to implement 2 stacks in an array?