Skip to content

Instantly share code, notes, and snippets.

@sebjacobs
Created January 13, 2020 23:49
Show Gist options
  • Save sebjacobs/bb38532a6aa65ca1aaa563c3b9d3945c to your computer and use it in GitHub Desktop.
Save sebjacobs/bb38532a6aa65ca1aaa563c3b9d3945c to your computer and use it in GitHub Desktop.
Sortable LinkedList. It is worth noting that the swap function kind of cheats because it only swaps the data and not the actual nodes
import { Sortable } from "./Sortable";
class Node {
constructor(public data: number, public next: Node | null = null) {}
}
export class LinkedList implements Sortable {
head: Node | null = null;
constructor() {}
add(value: number): void {
const node = new Node(value);
if (!this.head) {
this.head = node;
return;
}
let tail = this.head;
while (tail.next) {
tail = tail.next;
}
tail.next = node;
}
get length(): number {
if (!this.head) {
return 0;
}
let length = 0;
let node = this.head;
while (node.next) {
node = node.next;
length++;
}
return length;
}
at(index: number): Node {
if (!this.head) {
throw new Error("Index out of bounds.");
}
if (index >= this.length) {
throw new Error("Index out of bounds.");
}
if (index < 0) {
throw new Error("Index out of bounds.");
}
let counter = 0;
let node = this.head;
while (node) {
if (counter === index) {
return node;
}
node = node.next;
counter++;
}
throw new Error("Index out of bounds.");
}
compare(leftIndex: number, rightIndex: number): boolean {
if (!this.head) {
throw new Error("List is Empty");
}
return this.at(leftIndex).data > this.at(rightIndex).data;
}
swap(leftIndex: number, rightIndex: number): void {
const leftNode = this.at(leftIndex);
const rightNode = this.at(rightIndex);
const leftNodeData = leftNode.data;
const rightNodeData = rightNode.data;
leftNode.data = rightNodeData;
rightNode.data = leftNodeData;
}
print(): void {
if (!this.head) {
return;
}
let node: Node | null = this.head;
while (node) {
console.log(node.data);
node = node.next;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment