Prepare Interview

Mock Exams

Make Homepage

Bookmark this page

Subscribe Email Address

Core Java Interview Questions and Answers

Question: What's the difference between a queue and a stack?
Answer: Stacks works by last-in-first-out rule (LIFO), while queues use the FIFO rule.

You can think of a queue like a line at the bank. The first person to get there will get to the teller first. If a bunch of people come while all the tellers are busy, they stand in line in the order in which they arrived. That is to say, new people (items) are added to the end of the line and the first person in line is the only one who is called to a teller. In real life this is known as "first come, first served." In programming terms it's known as first-in-first-out, or FIFO.

You can think of a stack like a deck of cards. You can put down cards into a pile on your table one at a time, but if you want to draw cards, you can only draw them from the top of the deck one at a time. Unlike a queue, the first card to be put down is the last card to be used. This is known as first-in-last-out, or FILO (also called LIFO for last-in-first-out).

A queue is a first-in-first-out data structure. When you add an element to the queue you are adding it to the end, and when you remove an element you are removing it from the beginning.

A stack is a first-in-last-out data structure. When you add an element to a stack you are adding it to the end, and when you remove an element you are removing it from the end.
Is it helpful? Yes No

Most helpful rated by users:

©2024 WithoutBook