Skip to content

Instantly share code, notes, and snippets.

@mustafadalga
Created March 20, 2022 11:40
Show Gist options
  • Select an option

  • Save mustafadalga/1f448b3c2146aad6769f147a48aedf01 to your computer and use it in GitHub Desktop.

Select an option

Save mustafadalga/1f448b3c2146aad6769f147a48aedf01 to your computer and use it in GitHub Desktop.
Stack Data Structure Example
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class Stack {
constructor() {
this.first = null;
this.last = null;
this.size = 0;
}
push(value) {
const newNode = new Node(value);
if (this.first) {
newNode.next = this.first;
this.first = newNode;
} else {
this.first = newNode;
this.last = newNode;
}
this.size++;
return this.size;
}
pop() {
if (!this.size) return null;
const removedNode = this.first;
if (this.first == this.last) {
this.last = null;
}
this.first = removedNode.next;
this.size--;
return removedNode.value;
}
}
@mustafadalga
Copy link
Copy Markdown
Author

Another solution

class Stack {
  constructor() {
    this.items = [];
  }

  push(value) {
    this.items.push(value);
    return this.items.length;
  }

  pop() {
    return this.items.pop() ?? null;
  }

  peek() {
    return this.items[this.items.length - 1] ?? null;
  }

  isEmpty() {
    return this.items.length === 0;
  }

  length() {
    return this.items.length;
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment