Skip to content

Instantly share code, notes, and snippets.

@w8r
Created January 19, 2022 12:29
Show Gist options
  • Save w8r/dc99ac0e7fc0f584ce9dd4f29305c6aa to your computer and use it in GitHub Desktop.
Save w8r/dc99ac0e7fc0f584ce9dd4f29305c6aa to your computer and use it in GitHub Desktop.
Simple doubly-linked list
export class Node<T>{
data: T;
prev: Node<T> = null;
next: Node<T> = null;
constructor(data: T) {
this.data = data;
}
}
// create a node and optionally link it with previous one (in a circular doubly linked list)
export function insertNode<T>(data: T, last: Node<T> | null) {
const p = new Node(data);
if (last === null) {
p.prev = p;
p.next = p;
} else {
p.next = last.next;
p.prev = last;
last.next.prev = p;
last.next = p;
}
return p;
}
export function removeNode<T>(p: Node<T>) {
p.next.prev = p.prev;
p.prev.next = p.next;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment