DEV Community

Discussion on: Typescript Data Structures: Linked List

Collapse
 
matvs profile image
Mateusz Swiatkowski

Hi Gleb, nice and clear article :)

Could you elaborate on "Recursive functions are a great substitute of while loops for the tasks like traversing when we don't know the size of the list before we start iterating."?

I don't see what prior knowledge of the list size has to do with substituting while loop for a recursive call.

Traverse method could be easily implemented with while loop and it has an advantage of not worrying about exceeding a call stack.

public traverse(): T[] {
    const array: T[] = [];
    let currentNode = this.head;
    while(currentNode) {
        array.push(currentNode.data);
        currentNode = currentNode.next;
    }
    return array;
  }
Enter fullscreen mode Exit fullscreen mode

Also traverse method is a good candidate for using a technique called "tail recursion", but for JavaScript tail call is currently supported only by Safari/WebKit.

Collapse
 
glebirovich profile image
Gleb Irovich

Hey Mateusz, thanks for your feedback! Probably, the sentence is not very well structured. What I meant is that in the traverse example we don’t have prior knowledge of the size and therefore we cannot use for loops. However we can use a while loop or alternatively a recursive function.
It’s a great input regarding the call stack overflow πŸ‘πŸ‘πŸ‘, I definitely missed it out of sight, since I alway tend to be biased toward functional approaches.