So I'm needing to know how to write enqueue and dequeue. I need to understand what they look like, since I'm not allowed to use the built-in commands. My textbook is absolutely useless and gives me unnecessary information on how to write them.
1 Answer
Enqueue and dequeue are like lines at the bank. The first thing in is the first thing out. If you want to get in line, you get in line on one end, and if you want to get out, you get out on the other end. You can't get in or out anywhere else.
Usually, enqueue inserts at the first position of a list and dequeue removes at the last position - so let's go with that (though you could write it vice versa). For a linked list, to enqueue is the same as inserting at the first position, which is roughly:
Node oldFirst = this.first;
this.first = new Node(thing);
this.first.next = oldFirst;
size++;
Don't forget to set the .prev's properly, if it's doubly-linked. Dequeue is the same thing, but at the back. If you've got a this.last, then just mirror the above. If you don't, then just iterate across the elements until you find the one before the last one, put its .next in a temp variable, set it to null, and then return it.