Admittedly this seems like a silly question, but bear with me.
In a question I'm given relating to a Stack, we are to define a function that returns the item "on top" of the stack. To me, I don't know which side is the "top" because really, either side could be.
Also, I'm given a question relating to a Queue which asks us to define a function that returns the item "on the front" of the queue. Again, either side can be interpreted as the "front"
If the questions were reworded to ask "return the last item on the list" or the "first item on the list" this makes perfect sense, but unfortunately that is not the case.
So I would like to know: is there a definition for both "front" and "top" in terms of stacks/queues which are basically just lists, or are these terms ambiguous?
In the stack, we insert the element from one end with push operation and delete the element from the same end using pop operation. The end of the stack used to perform all the operations is called the top of the stack.
Considered as a linear data structure, or more abstractly a sequential collection, the push and pop operations occur only at one end of the structure, referred to as the top of the stack.
Get the last item of a list using list. To get the last element of the list using list. pop(), the list. pop() method is used to access the last element of the list.
We keep track of where we are going to be inserting with a special index called top . That is, the top is the index of the most recently added item. Thus, when the stack is empty, top == -1.
Is there a definition for both "front" and "top" in terms of stacks/queues which are basically just lists or are these terms ambiguous
The question is built on a false premise, that stacks/queues are "basically just lists".
Take a look at this picture, which shows how python lists are stored in memory (CPython)
(image source: here)
The implementation is actually nothing much like a stack or a queue, and the actual list objects can be all over the place in memory.
This one's pretty clear-cut: if someone speaks about the "top" of the stack, they would be referring to the item that was most recently added to the stack. That's the item you'll get if you "pop" off the stack.
This one's a bit more airy-fairy. If someone refers to the front of the queue, they probably mean the item which was added earliest, since queues are usually implemented "FIFO" (first in first out). But, it does depend on the implementation, for example there is also a LIFO Queue in python, which orders more like a stack. To make matters worse, there are also deques (double-ended queues) so you really need to have more context to understand this bit of CS jargon.
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