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 push and write some test code to ensure that it's working.

Solution

The push method is a bit more involved.

  • First, given a value, we want to create a ListNode with that value, referenced by newNode.
  • Next, we must consider two scenarios: an empty stack and a non-empty stack.
    • If the stack has no elements, directly assign newNode as the top node.
    • If the stack is not empty:
      • Set the next property of newNode to point to the current top node.
      • Update the top pointer to reference newNode.

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

myStack.push(1)

myStack.push(2)

myStack.push(3)

// some code above

push(value) {
  const newNode = new ListNode(value);
  if (!this.top) {
    this.top = newNode;
  } else {
      newNode.next = this.top;
      this.top = newNode;
  }
}

We can simplify this implementation significantly. Remember that our ListNode class allows us to pass in a next value when we create a new node. As a result, we can assign the current top to our new node's next value, handling both scenarios with one action:

// some code above

push(value) {
  this.top = new ListNode(value, this.top);
}

If the stack is empty, this.top is null, which is the default value that ListNode uses when we don't pass in a next argument. If the stack is not empty, this.top references the node that should be referenced by newNode's next pointer.

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...