DSA, Database System & Operating System β Data Structure, Lists, Linked Lists and Trees, NEC licence examination syllabus (Nepal Engineering Council).
Your browser's back button and a printer's job queue are running these two structures right now.
RuleLast In, First Out β like a stack of plates, you can only take from the top.
OperationsPush (add to top), Pop (remove from top), Peek (look at top without removing).
Real exampleYour browser's "back" button β the most recently visited page is the first one you go back to.
RuleFirst In, First Out β like a real queue at a shop, whoever arrived first gets served first.
OperationsEnqueue (add to back), Dequeue (remove from front).
Circular queueWraps the back around to the front position once space frees up, avoiding wasted array space that a simple queue would leave behind.
Implement a queue with an array, a front index and a rear index, and a problem appears immediately.
One change fixes it: advance the indices modulo the array size, so they wrap around to the start instead of running off the end.
rear = rear + 1 without it is the single commonest error in queue implementation questions.The circular queue creates one subtlety, and questions target it directly.
When the queue is empty, front == rear. When it is completely full and rear has wrapped all the way round, front == rear again. The same test gives opposite answers, so the two states cannot be distinguished by the indices alone.Keep a countTrack the number of items. Empty is count == 0, full is count == SIZE. Uses the whole array, at the cost of maintaining one extra variable.
Sacrifice one slotDeclare the queue full when (rear + 1) % SIZE == front, so rear never quite catches front. Simpler, but one slot is permanently wasted.
Every stack and queue operation touches only the ends β push and pop at the top, enqueue at the rear and dequeue at the front. Nothing is searched and nothing is shifted, so all of them are O(1) regardless of how many items are stored.
Create a free account to tick topics off, take notes as you read, watch the video lessons and get a day-by-day study plan built around your exam date.
Loadingβ¦