Created
June 20, 2023 09:50
-
-
Save alexsoyes/036305636c5a1dbc627e084e302aa913 to your computer and use it in GitHub Desktop.
Exemple TypeScript : Listes chaînées
This file contains hidden or 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
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