+ 1

Why stack is stack ?

Hi We have memory layout of heap and stack... But we all know that function call and operations are implemented on stack data structure... Can it be implemented using queue? Why only lifo is implemented instead of FIFO..

17th Jun 2020, 12:57 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
3 Respostas
0
No, it cannot be implemented using queue bcoz the last function called should return first.. For eg. int get() { int x; cin>>x; return sqr(x); } int sqr(int y) { return y*y; } Here, in this program first get() will be called from main, and then it will call sqr()..Now, if queue is being used then bcoz of FIFO when sqr's return statement will execute, it will not be removed from queue as it follows FIFO, when get's return is executed both the function will end i.e first get() will be removed then sqr()..here it looks like it is easy and doesn't change in behavior, but when executing recursion using queue, it will pile up number of functions even if they have been executed, and will only be removed once the first function to call them executes return statement..So stack is more useful than queue in terms of memory..
17th Jun 2020, 1:08 PM
Alaska
Alaska - avatar
+ 1
Hi Alaska , thank you for very descriptive and clear answer
17th Jun 2020, 1:14 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 1
Ketan Lalcheta Ehh no problem, its my duty to share my knowledge with others😊 Happy coding
17th Jun 2020, 1:57 PM
Alaska
Alaska - avatar