Stacks and Queues Building stacks and queues
189. Implement a Queue with a Linked List
A queue hands values back in the order they went in: the value that has waited longest leaves first. Build a
queue of integers on a singly linked list. Write a class LinkedQueue with a constructor and four methods:
LinkedQueue()creates an empty queue.enqueue(value)addsvalueat the back of the queue.dequeue()removes the value at the front of the queue and returns it. If the queue is empty, it returns-1and changes nothing.front()returns the value at the front without removing it, or-1if the queue is empty.size()returns the number of values in the queue.
Keep each value in a node of your own, which holds the value and a link to the next node. Do not use an array, or a library queue, deque or list. The queue has no capacity: every enqueue adds its value. Each method must run in O(1) time.
Your class is tested by replaying a list of calls on a new LinkedQueue(). ops[i] names the i-th call:
"enqueue", "dequeue", "front" or "size". The enqueues take their values from values in order, so
the first enqueue is given values[0], the second values[1], and so on. The answer is the list of every
value that dequeue, front and size return, in the order of the calls.
In C# and Go the methods are Enqueue, Dequeue, Front and Size. Go creates the queue with
Constructor(), and Rust with LinkedQueue::new(). The names in ops are the same in every language.
Example 1
Input: ops = ["enqueue",
"enqueue",
"enqueue",
"front",
"dequeue",
"enqueue",
"size",
"dequeue",
"dequeue",
"dequeue",
"size"]
values = [5, 3, 8, 6]
[5,5,3,3,8,6,0]Explanation: front reads 5, the oldest value, and dequeue removes it. After 6 goes in, the queue holds 3, 8 and 6.
They leave in the order they came, and the queue ends empty.
Example 2
Input: ops = ["dequeue",
"front",
"size",
"enqueue",
"dequeue",
"dequeue",
"size"]
values = [0]
[-1,-1,0,0,-1,0]Explanation: On an empty queue, dequeue and front return -1 and change nothing. The 0 that goes in later is a real
value, so dequeue returns 0 for it.
Example 3
Input: ops = ["enqueue",
"dequeue",
"enqueue",
"enqueue",
"front",
"size",
"dequeue"]
values = [1000000000, 7, 7]
[1000000000,7,2,7]Explanation: The first dequeue empties the queue, and the next two enqueues fill it again. The two 7s are separate
values, so size is 2.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ ops.length ≤ 2 × 105- Each
ops[i]is"enqueue","dequeue","front"or"size". values.lengthequals the number of"enqueue"calls inops.0 ≤ values[i] ≤ 109
Clarifying questions
What you would ask an interviewer before writing any code.