DEV Community

miku86
miku86

Posted on

2

JavaScript Data Structures: Stack: Recap

Intro

Last time, we added the last method.

I hope you learned something about the concept of a Stack and tried your best to implement it on your own.


Thoughts about the Stack

We implemented the Stack using a Singly Linked List.

The Stack data structure is a very important concept, because we use it all the time.

The fundamental difference to the Singly and Doubly Linked List is the fact, that we only add and remove a node to/from the top of the Stack, so we use the "Last In, First Out"-Principle.

Examples in real life are a stack of cards, a pile of dishes, a browser history.

  • Access: O(N)
  • Search: O(N)
  • Insert: O(1)
  • Remove: O(1)

Final Implementation

Our Stack has these methods:

  • push, to add a node to the top of the stack
  • pop, to remove the top node from the stack
class Node {
  constructor(value) {
    this.value = value;
    this.next = null;
  }
}

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

  push(value) {
    const newNode = new Node(value);

    if (!this.length) {
      this.last = newNode;
    } else {
      newNode.next = this.last;
      this.last = newNode;
    }

    this.length += 1;
    return newNode;
  }

  pop() {
    if (!this.length) {
      return null;
    } else {
      const nodeToRemove = this.last;
      this.last = nodeToRemove.next;
      nodeToRemove.next = null;

      this.length -= 1;
      return nodeToRemove;
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Further Reading


Next Part

Now that we have looked at the Stack, we will take a look at the Queue.

Don't miss interesting stuff, subscribe!

Top comments (0)

Need a better mental model for async/await?

Check out this classic DEV post on the subject.

⭐️🎀 JavaScript Visualized: Promises & Async/Await

async await

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay