You are here:

C/Implementing 2 stacks with one array

Advertisement


Question
QUESTION: How would you go about implementing 2 stacks with one array? For example, the user enters in a number, then the user decides which stack to place the number in. This goes on all the way until the user enters a 0, which will display all the numbers. Thank you for your time.
ANSWER: Hi Jared

Even I have never faced a question like this before but i think this could be done with a little bit of trick i am considering two cases as follows:

case 1: both the stack contains positive numbers
then you can separate the contents using a negative sign before the number suppose you wanna store 2 in both the stacks then you place 2 on the first position of the array and -2 in the second position where -sign indicates values stored in the second array.

case 2: both the array contains mixed elements
then you can divide the array into two halves say an array of size 10 then use 0 to 4 for first array and 5 to 9 for the second array and then display the contents of the array accordingly.

If my solution is not helpful for your problem please feel free to revert back to me so that i can provide you with a mch concrete solution next time.

regards
Joydeep Bhattacharya

---------- FOLLOW-UP ----------

QUESTION: All the numbers are positive integers. Ok, what i'm trying to do is use a pair of stacks in one class. I want the user to first, ask how many numbers will be entered (and this will be the size of the array),second, ask the user for a number, and then the user chooses which stack to store the number in. This will continue until the user enters a 0 for a number, which will print out all the numbers. I can't figure it out. Thank you so much for helping me.

Answer
Hi Jared

What i suggest you is to use four flag variables to mark the start position of the first stack and end position and similarly for the second also now what you can do is to efficiently use the loop to handle the situation somewhat like this for(i=stackstart1;i<=stackend1;i++) for the first array and similarly for the second array also in case if you find it difficult to code it down then do let me know so that I can code it down for you.

Please don't hesitate to get back for me with any doubts and queries.

regards
Joydeep Bhattacharya

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Joydeep Bhattacharya

Expertise

Ability to solve C and Data Structure problems and puzzles with simple and easy to understand logic.

Experience

C, C++, Java, Data Structure, PHP, Web Designing

Organizations
http://www.scodz.com Designation: webmaster

Publications
http://www.scodz.com

Education/Credentials
Master of Computer Applications

Past/Present Clients
http://analysingc.50webs.com http://www.funforu.com

©2012 About.com, a part of The New York Times Company. All rights reserved.