Skip to content

Instantly share code, notes, and snippets.

@alexsoyes
Created June 20, 2023 09:50
Show Gist options
  • Save alexsoyes/036305636c5a1dbc627e084e302aa913 to your computer and use it in GitHub Desktop.
Save alexsoyes/036305636c5a1dbc627e084e302aa913 to your computer and use it in GitHub Desktop.
Exemple TypeScript : Listes chaînées
class ListNode<T> {
value: T;
next: ListNode<T> | null;
constructor(value: T) {
this.value = value;
this.next = null;
}
}
class LinkedList<T> {
head: ListNode<T> | null;
tail: ListNode<T> | null;
constructor() {
this.head = null;
this.tail = null;
}
addToTail(value: T): void {
const newNode = new ListNode(value);
if (!this.head) {
this.head = newNode;
this.tail = newNode;
} else {
this.tail!.next = newNode;
this.tail = newNode;
}
}
}
const linkedList = new LinkedList<number>();
linkedList.addToTail(1);
linkedList.addToTail(2);
linkedList.addToTail(3);
console.log(linkedList); // { head: ListNode { value: 1, next: ListNode { value: 2, next: ListNode { value: 3, next: null } } }, tail: ListNode { value: 3, next: null } }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment