Search code examples
data-structureslinked-liststackqueue

Stacks, queues and linked lists


I have started learning Data Structures recently, and just had my own linked list implementation.

Now I stumbled upon two new data structures: stack and queue.
From what I have learned so far
stack is a linked list that allows insertion / removal only from its tail, and
queue is a linked list that allows insertion only at its tail and removal only from its head.

My questions are:
Why would I use these two data structures instead of a regular linked list that allows insertion and removal from anywhere?
Also, Why are these two data structure classified as independent data structures rather than "limited access linked lists"?


Solution

  • Stacks and queues have their own reason of existence. A stack is a FILO (First In Last Out) or LIFO (either ways) data structure that could be implemented using arrays, linked lists or other forms. Consider browser history. You navigate to Site A -> then B -> then C -> D. As a user moves ahead, you first push (insert at tail) the list of websites. This ensures that the current site is always at the top of the stack. Stack in action

    Then when the user hits back button, you pop the one at the top (removing from tail - the same end used for insertion) which gives the last visited site - C. Thus the concept of First In (which was Site A) and Last Out (the last one to go in was Site D which in turn became the first one to go out)

    Similar could be said for queue which is FIFO (First In First Out). Consider the example of job queue. When performing a job, you would (not considering any optimization algorithms) serve the one first to arrive. This makes queue an excellent data structure to process jobs on a first come first serve basis.

    In both the cases, you wouldn't want an arbitrary removal or insertion of elements at any index. No, that would result in an undesirable behaviour. Hence, the need for stack/queue. I would again emphasize that stacks/queues can be implemented by enforcing restrictions on linked lists.

    Sorry for the poor image quality - I just drew it in paint.