0

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
  • Why didn't you googled it? Commented Mar 14, 2015 at 22:07

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this definitely helps. So do you not need to do anything with the back pointer with enqueue?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.