no-stack-dub-sack / cs-playground-react

In-Browser Algorithm and Data Structures Practice
http://cs-playground-react.surge.sh/
MIT License
520 stars 91 forks source link

push, pop, or peek method in current stack implementation are O(n) #13

Closed kingstenbanh closed 6 years ago

kingstenbanh commented 6 years ago

I love your project! It already helps me sharpening my rusty CS skills. Stack is last in first out. With the way you push new value into the stack, a new value gets stacked below the old value instead of being on top of the stack.

O(n)

stack.push(1)
(1) =======

stack.push(2)
(1) =======
(2) =======

stack.push(3)
(1) =======
(2) =======
(3) =======

O(1)

stack.push(1)
stack.push(2)
stack.push(3)
(3) =======
(2) =======
(1) =======

When call stack.pop(), stack.push(), or stack.peek(), you have to recursively loop down to the last value and remove/add/peek it from/to the stack, which does not have O(1). Here is my propose solution:

class Stack {
    constructor() {
        this.root = null;
        this.size = 0;
    }

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

        if (this.root === null) {
            this.root = node;
        } else {
        node.next = this.root;
            this.root = node;
        }

        this.size++;
    }

    pop() {
        if (this.isEmpty()) {
            return;
        }

        const value = this.root.value;
        this.root = this.root.next;
        this.size--;

        return value;
    }

    peek() {
        return this.root.value;
    }

    isEmpty() {
        return this.size === 0;
    }

    clear() {
        this.root = null;
        this.size = 0;
    }
}

Since this is for educational purpose, we don't want to mislead others.

no-stack-dub-sack commented 6 years ago

@kingstenbanh wow, nice catch! And this is why I mentioned in the README.md and in the article, some of my solutions are less than perfect, so if anyone can improve, I'm happy to listen!

This makes total sense, though, and is a much simpler way of doing it. I had the last-in-first-out part right, but was just going about it in a very inefficient way... This is much better.

Are you interested in making a PR? If so, I would gladly accept it.

Thanks for the props, too, btw! Glad you are finding the project useful.

Since this is for educational purpose, we don't want to mislead others.

And yes, I totally agree.