Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array implementation using stack

A language has not array as a data type but it has stack as a data type and one can declare stack's; and push, pop and isempty operations are defined.
So how can we implement array using two stacks and above operations?

like image 624
arpit Avatar asked Feb 06 '26 09:02

arpit


2 Answers

Horribly inefficient - but:

Stack 1 Contains the details Stack 2 is empty.

To go through the array, Pop Stack 1 , when you want the next one, push the previous one into stack 2 and pop stack 1 again. Repeat until 'isempty'.

If you want the Nth value, pop the not empty stack N times while pushing the unneeded ones into the other stack. Then when you're done playing with it, empty it into the other stack. Note that this;ll flip the order.

like image 122
Haedrian Avatar answered Feb 08 '26 23:02

Haedrian


With two stacks you can get some sort of random access (which is what you're interested in an array) like this:

  • Put everything on a stack.
  • Every time you have to access something that's not the top of the stack (pop), you pop all elements from this stack and push them in order to the second one.

By passing elements from one stack to another you simulate iteration.

like image 21
leo Avatar answered Feb 08 '26 22:02

leo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!