Skip to content

Instantly share code, notes, and snippets.

@SparrowMike
Created November 6, 2022 02:47
Show Gist options
  • Save SparrowMike/816ccc1576bcfb4b3366e0b9f4554fde to your computer and use it in GitHub Desktop.
Save SparrowMike/816ccc1576bcfb4b3366e0b9f4554fde to your computer and use it in GitHub Desktop.
class Node {
constructor(val) {
this.val = val;
this.next = null;
}
}
class SinglyLinkedList {
constructor() {
this.head = null;
this.tail = null;
this.length = 0;
}
traversy() {
let current = this.head
while(current) {
console.log(current.val)
current = current.next;
}
}
print() {
let arr = [];
let current = this.head;
while (current) {
arr.push(current.val)
current = current.next
}
console.log(arr)
}
push(val) {
let newNode = new Node(val);
if (!this.head) {
this.head = newNode;
this.tail = this.head;
} else {
this.tail.next = newNode;
this.tail = newNode;
}
this.length ++;
return this
}
pop() {
if (!this.head) return undefined;
let current = this.head;
let newTail = current;
while(current.next) {
newTail = current;
current = current.next;
}
this.tail = newTail;
this.tail.next = null;
this.length--;
if (this.length === 0) {
this.head = null;
this.tail = null;
}
return current;
}
shift() {
if (!this.head) return undefined;
let currentHead = this.head;
this.head = currentHead.next;
this.length--;
if (this.length === 0) {
this.tail = null;
}
return currentHead;
}
unshift(val) {
let newNode = new Node(val);
if (!this.head) {
this.head = newNode;
this.tail = this.head;
} else {
newNode.next = this.head;
this.head = newNode;
}
this.length ++;
return this;
}
get(index) {
if (index < 0 || index >= this.length) return null;
let counter = 0;
let current = this.head;
while (counter !== index) {
current = current.next;
counter++;
}
return current
}
set(index, val) {
let target = this.get(index)
if (target ) {
target.val = val;
}
return this;
}
insert(index, val) {
if (index < 0 || index > this.length) return false;
if (index === 0) return !!this.unshift(val);
if (index === this.length) return !!this.push(val);
let newNode = new Node(val);
let prev = this.get(index - 1);
let next = prev.next;
prev.next = newNode;
newNode.next = next;
this.length--;
return true
}
remove(index) {
if (index < 0 || index >= this.length) return undefined;
if (index === this.length - 1) return !!this.pop();
if (index === 0) return !!this.shift();
let prev = this.get(index - 1);
let removed = prev.next;
prev.next = removed.next;
this.length--;
return removed
}
reverse() {
let node = this.head;
this.head = this.tail;
this.tail = node;
let next = null;
let prev = null;
for (let i = 0; i < this.length; i++) {
next = node.next;
node.next = prev;
prev = node;
node = next
}
return this;
}
}
let list = new SinglyLinkedList()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment