The problem. Build a queue on a singly linked list of ListNodes (each has a val and a next). Support enqueue(x), dequeue() (remove and return the front item, or -1 if empty), front() (the front item, or -1 if empty), isEmpty() and size(). A linked list never runs out of slots, so there is no capacity to manage.
enqueue(10) enqueue(20) front() -> 10
dequeue() -> 10 size() -> 1
dequeue() -> 20 dequeue() -> -1 (empty)A linked list can only cheaply change things it holds a pointer to. So the questions are: which end is the front, which is the back, and which pointers do we keep?
Members only · free account
The rest of this lesson, with 6 more sections, 4 drawings, a dry-run simulator and code in JavaScript, Python, Java and C++, opens with a free account.
Not ready yet? The Arrays course is free to read, no account needed.
In the rest of this lesson