← Blog

JavaScript Data Structures: Stack: Push / Add a new node

December, 2019

Intro

Last time, we learned what a Stack is and set it up.

Today, we learn how to push / add a new node on top of the Stack.


Starter Code

We start with the code from the last part.

class Node {
  constructor(value) {
    this.value = value;
    this.next = null;
  }
}

class Stack {
  constructor() {
    this.length = 0;
    this.last = null;
  }
}

Thoughts

First, we should think about the constraints and possibilities:

If the Stack is empty:

  • create a new node
  • set the new node as the last node
  • increase the stack’s length by 1
  • return the new node

All remaining cases:

  • create a new node
  • set the current last node as the new node’s next node
  • set the new node as the new last node
  • increase the stack’s length by 1
  • return the new node

Example

// current stack:
A <== B (last)

// desired stack:
A <== B        <== C (last)

Steps:

// current stack:
A <== B (last)

// set the current last node as the new node's next node
A <== B (last) <== C

// set the new node as the new last node
A <== B        <== C (last)

// desired stack:
A <== B        <== C (last)

=> stack after last step equals the desired stack


Implementation

class Node {
  constructor(value) {
    this.value = value;
    this.next = null;
  }
}

class Stack {
  constructor() {
    this.length = 0;
    this.last = null;
  }

  push(value) {
    // create a new node
    const newNode = new Node(value);

    if (!this.length) {
      // stack is empty, therefore set the new node as the last node
      this.last = newNode;
    } else {
      // set the current last node as the new node's next node
      newNode.next = this.last;
      // set the new node as the new last node
      this.last = newNode;
    }

    // increase the stack's length by 1
    this.length += 1;
    // return the new node
    return newNode;
  }
}

Result

Let’s have a look how to use the push method and its results.

const newStack = new Stack();

// should be empty
console.log(newStack);
// Stack { length: 0, last: null }

// one new node
console.log(newStack.push("A"));
// Node { value: 'A', next: null }

// should have one node
console.log(newStack);
// Stack { length: 1, last: Node { value: 'A', next: null } }

// one new node
console.log(newStack.push("B"));
// Node { value: 'B', next: Node { value: 'A', next: null } }

// should have two nodes
console.log(newStack);
// Stack {
//   length: 2,
//   last: Node { value: 'B', next: Node { value: 'A', next: null } }
// }

Next Part

We will implement our next method to pop the last node.

If you want to get notified, subscribe!


miku86

Hi! I'm Michael 👋 I'm a problem solver and mentor. My goal is to build great products and help you to become a better developer.