Hack Reactor — Day 3
So I wanted to write a blog right now because I just finished up a Help Desk with Hera -(You rock Hera). I was working on Queues, and was pretty stuck on constructing “dequeue” correctly. I initially tried the same approach that I used on constructing Stack’s pop method, but that didn’t work. I think from working with Hera, I now have a good approach to understanding this.
Instead of using a typical counter that would increment with each enqueue, I used a front variable and a back variable. If you think of it as a line for coffee, every time a new person joins the line, they’re adding 1 to the back of the line. Easy enough. The thing that was hard for me to grasp was the front variable. You are initially setting the front to be zero, but you have to remember that you’re using this to reference the first key / value of the storage object. The zero has nothing to do with the number zero in regards to it being a number. The front then increments, making the front the number “1”, or the next person in the coffee line.
It does not matter that the front is no longer zero. Maybe some people would be like “Yeah obviously…” but it took me a good bit to figure that out. Each time you dequeue, you lose the current front, and the next in line becomes the front. It’s incredibly simple, and for me it was incredibly mind blowing. There are other things that go into this, but that concept for me was huge. More to come!