trekhleb / javascript-algorithms

📝 Algorithms and data structures implemented in JavaScript with explanations and links to further readings
MIT License
185.03k stars 29.84k forks source link

Add 'size()' method in linked list data structure and also written te… #1047

Open bhaveshmhadse opened 1 year ago

bhaveshmhadse commented 1 year ago

Update file src/data-structures/linked-list/LinkedList.js and src/data-structures/linked-list/test/LinkedList.test.js

Before

After

   /**
   * @returns {Number}
   */
  size() {
    // If head is null the size of linked list will be -1 or 0, So here we return -1.
    if (!this.head) {
      return -1;
    }

    let size = 0;
    let currentNode = this.head;

    // Traverse to the linked list and update the size.
    while (currentNode) {
      size += 1;
      currentNode = currentNode.next;
    }

    return size;
  }

Before

After

  it('should return the size of linked list', () => {
    const linkedList = new LinkedList();

    linkedList.append(1);
    linkedList.append(2);
    linkedList.append(3);

    expect(linkedList.size()).toBe(3);
  });