translate arrToLinkedList method

This commit is contained in:
steak-zhuo
2023-01-08 12:47:33 +08:00
parent 01b95bc0f9
commit a7a3618ee0
2 changed files with 30 additions and 11 deletions
+15
View File
@@ -14,4 +14,19 @@ export default class ListNode {
this.val = val === undefined ? 0 : val;
this.next = next === undefined ? null : next;
}
/**
* Generate a linked list with an array
* @param arr
* @return
*/
arrToLinkedList(arr: number[]) {
const dum: ListNode = new ListNode(0);
let head = dum;
for (const val of arr) {
head.next = new ListNode(val);
head = head.next;
}
return dum.next;
}
}