GitHub Repository Submission

When using GitHub mode, paste your repository URL below and click Save URL to store it. The saved URL will be automatically included with every message you send until you choose to clear it. Learn more

Your GitHub repository URL is saved. LSBot will automatically fetch your latest code from this repository for each message. To change the URL, clear it first and save a new one.

Exercise 2

Implement enqueue and write some test code to ensure that it's working.

Solution

The enqueue method is more challenging.

  • First, create a new ListNode with the given value.
  • If the queue is empty (no front node), the new node becomes both the front and back of the queue.
  • If the queue is not empty:
    • Link the next property of the current back node to the new node.
    • Update the back to point to the new node.

Assuming we have created a queue, let's see how adding the first 3 elements would look visually:

myQueue.enqueue(1)

We start by creating a new ListNode with 1 as the value. Because front is null when our queue is empty, we'll assign both front and back to our new node.

myQueue.enqueue(2)

Again, we start by creating our new node, newNode. Now that our list is not empty, we'll assign the next property of the back node (the last node in our queue) to newNode. This puts our new node 'behind' the end of our queue. We finish by assigning back to the new end of our queue.

myQueue.enqueue(3)

Adding yet another node follows the same process as the previous call to enqueue. We create a new node, update the next pointer of back, and reassign back to newNode.


// some code above

enqueue(value) {
  const newNode = new ListNode(value);
  if (!this.back) {
    this.front = this.back = newNode;
  } else {
    this.back.next = newNode;
    this.back = newNode;
  }
}

Hi! I'm LSBot. I can help you think through the selected exercise by giving you hints and guidance without revealing the solution. Your code from the editor will be automatically detected. Want to know more? Refer to the LSBot User Guide .

Detected solution
Loading...

Submit your solution for LSBot review.

Hi! I'm LSBot. Your code from the editor will be automatically detected. I'll review your solution and provide feedback to help you improve. Ask questions about your solution or request a comprehensive code review. Want to know more? Refer to the LSBot User Guide .

Detected solution
Loading...