Skip to content

Instantly share code, notes, and snippets.

@JWKnapp
Created October 29, 2018 19:55
Show Gist options
  • Save JWKnapp/fcbc2274ab6be560afc6f8d3bd30c453 to your computer and use it in GitHub Desktop.
Save JWKnapp/fcbc2274ab6be560afc6f8d3bd30c453 to your computer and use it in GitHub Desktop.

Prompt

Given an existing (doubly) linked list class, implement a stack class and a queue class. Do so via classical inheritance and then do so separately via composition. Then talk about which you would choose in this situation and why.

The linked list class has instance methods for addToHead, addToTail, removeFromHead, and removeFromTail.

The queue class should have instance methods for enqueue and dequeue. The stack class should have instance methods for push and pop.

Solution

Via inheritance:

class Queue extends DoublyLinkedList {
  enqueue (value) {
    return this.addToHead(value);
  }
  dequeue () {
    return this.removeFromTail();
  }
}
class Stack extends DoublyLinkedList {
  push (value) {
    return this.addToTail(value);
  }
  pop () {
    return this.removeFromTail();
  }
}

Via composition:

class Queue {
  constructor () {
    this._linkedList = new DoublyLinkedList();
  }
  enqueue (value) {
    return this._linkedList.addToHead(value);
  }
  dequeue () {
    return this._linkedList.removeFromTail();
  }
}
class Stack {
  constructor () {
    this._linkedList = new DoublyLinkedList();
  }
  push (value) {
    return this._linkedList.addToTail(value);
  }
  pop () {
    return this._linkedList.removeFromTail();
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment