I am reading datastructures and see stack and queue but i do not get enough examples in computer systems or web development or specific problems where i should use a stack or queue or a tree etc.
Stacks are used by most (all?) programming languages to keep track of the state of the program when sub-routines are called.
Explanation: The code of your program is stored in main memory. The CPU has an instruction pointer that always points to the next instruction that will be executed. When an instruction has been executed, this pointer is increased by one, to point to the next instruction.
When your program enters a sub-routine, the instruction pointer jumps to some other address. When that routine is finished, it has to know where it left of. So, the last address before the jump is pushed on the stack. When the function is finished, the topmost item on the stack will be that address.
This is also the reason why excessive recursion can lead to a stack-overflow. Too many nested calls lead to many return addresses being pushed on the stack, but none are removed.
Read more on Wikipedia.
Trees can be used for many things, for instance binary search trees.
Queues are common whereever something needs to be handled on a first-come-first-serve principle. Network packets, I/O requests, etc.
You want a stack when you need to re-use the last item you put on it again. I can't find a nice example off the top of my hat, but it's used e.g. in converting normal mathematical expressions into RPN or for storing nodes when doing a depth-first search in a graph.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With