Stacks and Queues – Why Are They Needed?

data structuresjavalinked listtheory

I don't see the reason to have classes for stacks, queues and deques if we have the data structure linked list, since a linked list can act as both a stack and a queue (and always has the functions of both, if not just named differently).

So this brings forth my question,

Is there a specific reason I should use stacks and queues over a linked list besides readability?

last tidbit, I program in Java and .Net

Best Answer

Stacks and queues are ways of working with contiguous memory. Linked lists are not. Now sure, any problem that you can solve with one structure you could solve with another and slap enough abstraction on it that you couldn't tell the difference. So what's the real difference? Performance. Choosing between these structures is about what you DON'T do with them because they don't do that well.

Linked lists make insertions into their middle easy. They make traversing hard.

Stacks and queues prefer to do insertions and removal at an end.

None make it impossible to do anything since you can rebuild the entire structure. The issue is the cost that comes at.

One thing that's helped me along the way is this little guy:

enter image description here

Here's one that includes the less popular structures:

enter image description here

Under the hood it's all one big array called random access memory. Using these structures doesn't change that. But if you can predict what you don't need you can choose the right structure that will help you use that memory very well.

Related Topic