Created
January 19, 2022 12:29
-
-
Save w8r/dc99ac0e7fc0f584ce9dd4f29305c6aa to your computer and use it in GitHub Desktop.
Simple doubly-linked list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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