Skip to content

Instantly share code, notes, and snippets.

@esayler
Created December 7, 2016 16:24
Show Gist options
  • Select an option

  • Save esayler/6715343cc483f003da2c84564dfc6aad to your computer and use it in GitHub Desktop.

Select an option

Save esayler/6715343cc483f003da2c84564dfc6aad to your computer and use it in GitHub Desktop.
function List() {
this.head = null;
this.tail = null;
this._length = 0;
};
List.prototype.push = function(data) {
var newNode = new ListNode(data);
if (this.head === null && this.tail === null) {
this.head = newNode;
this.tail = newNode;
} else if (this.head !== null) {
this.tail.nextNode = newNode;
this.tail = newNode;
}
this._length += 1;
};
List.prototype.pop = function() {
if (this._length === 0) {
return null;
} else if (this._length === 1) {
this._length -= 1;
this.head = null;
var temp = this.tail;
this.tail = null;
return temp;
} else if (this._length > 1) {
this._length -= 1;
var temp = this.tail;
var prev = this.getSecondToLast();
this.tail = prev;
prev.nextNode = null;
return temp;
}
}
List.prototype.getSecondToLast = function() {
var prev = null;
var current = this.head;
while(current.nextNode !== null) {
prev = current;
current = current.nextNode;
}
return prev;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment