Skip to content

Instantly share code, notes, and snippets.

@AdilsonFuxe
Created September 26, 2022 14:42
Show Gist options
  • Save AdilsonFuxe/74bc8a771da19c38fb5370ce22ae7cc3 to your computer and use it in GitHub Desktop.
Save AdilsonFuxe/74bc8a771da19c38fb5370ce22ae7cc3 to your computer and use it in GitHub Desktop.
Linked List with javascript
var ListNode = function (val, next) {
this.val = val === undefined ? 0 : val;
this.next = !next ? null : next;
};
var MyLinkedList = function () {
this.head = null;
};
/**
* @param {number} index
* @return {number}
*/
MyLinkedList.prototype.get = function (index) {
let head = this.head;
if (head && index >= 0) {
let i = 0;
while (head) {
if (i === index) {
return head.val;
}
head = head.next;
i++;
}
}
return -1;
};
/**
* @param {number} val
* @return {void}
*/
MyLinkedList.prototype.addAtHead = function (val) {
const newNode = new ListNode(val, this.head);
this.head = newNode;
};
/**
* @param {number} val
* @return {void}
*/
MyLinkedList.prototype.addAtTail = function (val) {
let head = this.head;
while (head && head.next) {
head = head.next;
}
if (!head) {
this.addAtHead(val);
} else {
head.next = new ListNode(val, null);
}
};
/**
* @param {number} index
* @param {number} val
* @return {void}
*/
MyLinkedList.prototype.addAtIndex = function (index, val) {
const size = this.size();
if (index >= 0 && index <= size) {
let head = this.head;
let before = null;
let i = 0;
while (head && index != i) {
i++;
before = head;
head = head.next;
}
const node = new ListNode(val, null);
if (before === null) {
node.next = this.head;
this.head = node;
} else {
before.next = node;
node.next = head;
}
}
};
/**
* @param {number} index
* @return {void}
*/
MyLinkedList.prototype.deleteAtIndex = function (index) {
const size = this.size();
if (this.head && index >= 0 && index < size) {
let head = this.head;
let before = null;
let i = 0;
while (head && index != i) {
i++;
before = head;
head = head.next;
}
if (before === null) {
this.head = this.head.next;
} else {
before.next = head.next;
}
}
};
MyLinkedList.prototype.getList = function () {
let head = this.head;
let numbers = [];
while (head) {
numbers.push(head.val);
head = head.next;
}
return numbers;
};
MyLinkedList.prototype.size = function () {
let head = this.head;
let count = 0;
while (head) {
count++;
head = head.next;
}
return count;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment