Есть два способа найти длину связанного списка —
- Простой - циклический просмотр полного связанного списка до
next=null
- Рекурсивное увеличение длины до последнего
В этой статье я объясню оба способа.
Простой цикл
class Node { constructor(value) { this.value = value; this.next = null; } } class LinkedList { add(value) { let root = this.root; let node = new Node(value); if (root == null) { this.root = node; } else { while (root.next != null) { root = root.next; } root.next = node; } } length() { let root = this.root; let length = 0; while (root != null) { root = root.next; ++length; } return length; } } const list = new LinkedList(); list.add(5); list.add(51); list.add(52); console.log("length", list.length());
Рекурсивно
class Node { constructor(value) { this.value = value; this.next = null; } } class LinkedList { add(value) { let root = this.root; let node = new Node(value); if (root == null) { this.root = node; } else { while (root.next != null) { root = root.next; } root.next = node; } } lengthUsingRecursion() { const length = (root) => { if (root == null) { return 0; } return 1 + length(root.next); } return length(this.root); } } const list = new LinkedList(); list.add(5); list.add(51); list.add(52); console.log("length by recursion", list.lengthUsingRecursion());