A rather interesting analogy is that of a firearms magazine.
if we look at this picture:
It is easy to see that bullets can be inserted from the top, and only the topmost bullet is accessible. Such is a stack. A magazine works by LIFO (Last In First Out), and so does a Stack.
Furthermore, the four (five1) basic operations of a Stack are applicable:
- Push - adding a new element (bullet) to the top.
- Pop - remove the top element (bullet) from the stack (in the analogy, this is like shooting).
- Peek - looking at the first element of the stack (checking to make sure that the topmost bullet is correctly placed)
- Check if Empty - check if the stack is empty (in the analogy, this operation is checking if there are bullets left)
- (Initializing the stack - creating a new stack)
1The initializing of the stack isn't exactly a special operation a stack can do.
A stack is something used in programming when you need to keep a record of the history of versions. For example, many text editors use a stack data structure to save the changes made to the file. Also, revisions of posts on Stack Exchange have some form of a Stack (funny coincidence, isn't it?) to save the revisions (though I think the SE system uses partial functionality of a stack. I'll check that and edit this post when I have a definite answer about this particular part).
The very obvious usage of stack is, of course, the stack segment of computer memory. The call stack is, well, a call stack. (more on this can be seen here)
Another handy example is the browser back button. The browser has a stack with the links (technically, sort of cached versions) of pages you've been to. When pressing the "back" button, the stack's pop
function is called, and you get redirected to that. When a link is pressed, a new element is pushed
onto the stack.