Skip to content

Instantly share code, notes, and snippets.

@hkasera
Created June 17, 2014 18:11
Show Gist options
  • Save hkasera/063fe1b0e47a20a7ede6 to your computer and use it in GitHub Desktop.
Save hkasera/063fe1b0e47a20a7ede6 to your computer and use it in GitHub Desktop.
Singly Linked List and related operations in javascript
var Node = function (val) {
this.val = val || null;
this.next = null;
};
var SinglyLinkedList = function () {
this.head = null;
this.tail = null;
};
SinglyLinkedList.prototype.push = function (val) {
var newNode = new Node(val);
if (!this.head && !this.tail) {
this.head = newNode;
this.tail = newNode;
return;
}
newNode.next = this.head;
this.head = newNode;
};
SinglyLinkedList.prototype.indexOf = function (index) {
if (index < 0 || !this.val) {
return;
}
if (index === 0) {
return this.val;
}
if (this.next) {
return this.next.indexOf(--index);
}
return;
};
SinglyLinkedList.prototype.length = function () {
if (!this.val) {
return 0;
}
var tmplen = 1;
if (this.next) {
tmplen = 1 + this.next.length();
}
return tmplen;
};
SinglyLinkedList.prototype.toArray = function () {
if (!this.head) {
return [];
}
console.log(this.head);
var tmpArray = [],
tmpList = this.head;
while (tmpList) {
tmpArray.push(tmpList.val);
tmpList = tmpList.next;
}
return tmpArray;
};
SinglyLinkedList.prototype.toString = function () {
if (!this.head) {
console.log("empty");
return;
}
var tmpNode = this.head,
tmpList = [];
while (tmpNode) {
tmpList.push(tmpNode.val);
tmpNode = tmpNode.next;
}
console.log(tmpList.join("->"));
return;
};
SinglyLinkedList.prototype.pop = function () {
if (!this.head) {
return;
}
if (this.head.next) {
this.head = this.head.next;
} else {
this.head = null;
this.tail = null;
}
};
var sll = new SinglyLinkedList();
sll.push(6);
sll.push(7);
sll.push(8);
sll.toString();
sll.pop();
sll.pop();
sll.toString();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment