Why and when to use Stack or Queue instead of Arrays/Lists?
A stack is a linear data structure in which elements are accessed, inserted and deleted from one end called the top of the stack. Stack follows the LIFO ( Last In First Out) approach. Two basic operations on a stack are push and pop.
A queue is also a linear data structure in which elements are inserted from one end called the rear end and deleted from the other end called the front end. Queue follows FIFO ( First In First Out ) approach. Two basic operations on the queue are – enqueue and dequeue.
An array is a linear data structure that combines the data of the same type. It is a collection of similar data types in which elements are accessed with the help of indices. The elements in the arrays are stored in contiguous memory locations. Array is a static data structure with limited size.
Why and When stack or queue is used instead of arrays/lists:
Because they assist you in managing your data in a more specific manner than arrays and lists. It means you won’t have to wonder if someone placed an element in the midst of your list at random, messing up certain invariants when troubleshooting an issue.Random access is the nature of arrays and lists. They’re incredibly adaptable, but they’re also easily corruptible. If you wish to keep track of your data,It’s recommended to use those, previously implemented, collections when storing data as FIFO or LIFO.
- We use stack or queue instead of arrays/lists when we want the elements in a specific order i.e. in the order we put them (queue) or in the reverse order (stack).
- Queues and stacks are dynamic while arrays are static. So when we require dynamic memory we use queue or stack over arrays.
- Stacks and queues are used over arrays when sequential access is required.
- To efficiently remove any data from the start (queue) or the end (stack) of a data structure.
- When you want to get items out in the same order that you put them in, use a queue (FIFO)
- When you need to bring things out in the opposite order that they were put in, use a stack (LIFO)
Please Login to comment...