Skip to content

Instantly share code, notes, and snippets.

@mayashavin
Last active June 5, 2018 08:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mayashavin/371256858c61affe5810a4d71ece587d to your computer and use it in GitHub Desktop.
Save mayashavin/371256858c61affe5810a4d71ece587d to your computer and use it in GitHub Desktop.
function Node(value) {
this.value = value;
this.next = undefined;
}
function SLinkedList() {
var head = undefined;
var length = 0;
return {
insert: function(item) {
if (!item) return;
var node = new Node(item);
if (head) {
node.next = head;
}
head = node;
length++;
},
delete: function(value) {
var curr = head;
if (head.value === value) {
head = head.next;
return;
}
while (curr) {
if (curr.next) {
var next = curr.next;
if (next.value === value) {
curr.next = next.next;
length--;
break;
}
}
curr = curr.next;
}
},
search: function(value) {
var curr = head;
var found = undefined;
while (curr) {
if (curr.value === value) {
found = curr;
break;
}
curr = curr.next;
}
return found;
},
get size() {
return length;
},
print: function() {
var result = [];
var curr = head;
while (curr) {
result.push(curr.value);
curr = curr.next;
}
return result;
}
}
}
@risejs
Copy link

risejs commented Jun 5, 2018

Add a list length update at L26-L29

      if (head.value === value) {
        head = head.next;
        length--;
        return;
      }

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