0
\$\begingroup\$

How can I improve my singly linked list implementation?

"use strict";

var LinkedList = function(){
  this.head = null;
  this.tail = null;
  this.count = null;
}
var Node = function(value){
  this.value = value;
  this.next = null;
}

LinkedList.prototype.addToHead = function(value){
  var newNode = new Node(value);
  if(this.head) {
    this.next = this.head;
    this.head = newNode
    this.count++;
  }
  else this.tail = newNode
}
LinkedList.prototype.addToTail = function(value){
  var newNode = new Node(value);
  if(this.tail) {
    this.tail.next = newNode
  }
  else this.tail = newNode;
}
var ll = new LinkedList();
ll.addToHead(3);
ll.addToHead(4);
ll.addToHead(2);
ll.addToTail(6);
console.log(JSON.stringify(ll))

\$\endgroup\$
3
\$\begingroup\$

This doesn't appear to function correctly right now so it may actually belong on Stack Overflow rather than on Code Review.

Regardless, here are the issues I'm seeing:

  1. When you attempt to add values to the head of the list, they instead are getting added to the tail of the list since the head of the list is always null. The new value should always end up as the head of the list when it is added to the head of the list.

  2. Your code is a bit visually confusing since you are using this to refer to 2 different objects in the same code block.

  3. You are only incrementing the count of the list's elements inside the part of the addToHead which is unreachable, resulting in a count of null regardless of what you do. Instead the count should be incremented on any add interaction.

  4. There doesn't seem to be an interaction to remove an item from the list, either front or back. Being able to remove items from the list is a core part of the functionality.

For the full definition of what a singly linked list needs to support, see this page.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.