Stacks, Queues, and Related Lists

Recently, I began to study data structures , and I had my own implementation of a linked list .

Now I came across two new data structures: stack and queue .
From what I have learned so far
stack is a linked list that allows you to insert / remove only from its tail, and
queue - this is a linked list that allows you to insert only in the tail and remove only from the head.

My questions:
Why should I use these two data structures instead of the usual linked list that allows you to insert and delete from anywhere?
Furthermore, why are these two data structures classified as independent data structures and not as β€œlinked restricted access lists”?

+9
source share
2 answers

Stacks and queues have their own reason for being. The stack is a FILO (First In Last Out) or LIFO (in any case) structure, which can be implemented using arrays, linked lists, or other forms. Consider the browser history. You go to the site A β†’ then B β†’ then C β†’ D. When the user moves forward, you first click (paste in the tail) the list of sites. This ensures that the current site is always at the top of the stack. Stack in action

Then, when the user clicks the back button, you pop at the top (removal from the tail is the same end that is used for insertion), which gives the last site visited - C. Thus, the concept of First In (which was site A) and Last Out (the last of these was site D, which, in turn, was the first to come out)

The same can be said about the queue, which is FIFO (First In First Out). Consider an example of a job queue. When completing a task, you (not counting any optimization algorithms) should serve the first one. This makes the queue an excellent data structure for processing jobs based on the first feed.

In both cases, you do not want to arbitrarily delete or insert elements in any index. No, this will lead to unwanted behavior. Hence the need for a stack / queue. I would like to emphasize once again that stacks / queues can be implemented by forcibly restricting linked lists.

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

+18
source

The stack is basically a data structure that follows the LIFO (LAST FIRST OUTSIDE). A queue is a sequence that follows a FIFO (FIRST IN FIRST OUT).

In general, Stacks and Queues can be implemented using Arrays and Linked Lists .

The reason you use the Linked List to implement Stack is when you need functionality that includes the LAST IN FIRST OUT form, and you don't know how many elements this functionality needs. This way, you will use LinkedList dynamically create nodes, depending on the requirement.

The same applies to Queues

The reason they are independent is because they follow different principles, such as LIFO and FIFO.

+3
source

All Articles