Avatar of chynh

chynh's solution

to Linked List in the TypeScript Track

Published at Oct 07 2019 · 0 comments
Instructions
Test suite
Solution

Implement a doubly linked list.

Like an array, a linked list is a simple linear data structure. Several common data types can be implemented using linked lists, like queues, stacks, and associative arrays.

A linked list is a collection of data elements called nodes. In a singly linked list each node holds a value and a link to the next node. In a doubly linked list each node also holds a link to the previous node.

You will write an implementation of a doubly linked list. Implement a Node to hold a value and pointers to the next and previous nodes. Then implement a List which holds references to the first and last node and offers an array-like interface for adding and removing items:

  • push (insert value at back);
  • pop (remove value at back);
  • shift (remove value at front).
  • unshift (insert value at front);

To keep your implementation simple, the tests will not cover error conditions. Specifically: pop or shift will never be called on an empty list.

If you want to know more about linked lists, check Wikipedia.

Setup

Go through the setup instructions for TypeScript to install the necessary dependencies:

https://exercism.io/tracks/typescript/installation

Requirements

Install assignment dependencies:

$ yarn install

Making the test suite pass

Execute the tests with:

$ yarn test

In the test suites all tests but the first have been skipped.

Once you get a test passing, you can enable the next one by changing xit to it.

Source

Classic computer science topic

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

linked-list.test.ts

import LinkedList from './linked-list'

describe('LinkedList', () => {
  it('add/extract elements to the end of the list with push/pop', () => {
    const list = new LinkedList<number>()
    list.push(10)
    list.push(20)
    expect(list.pop()).toBe(20)
    expect(list.pop()).toBe(10)
  })

  xit('extract elements from the beginning of the list with shift', () => {
    const list = new LinkedList<number>()
    list.push(10)
    list.push(20)
    expect(list.shift()).toBe(10)
    expect(list.shift()).toBe(20)
  })

  xit('add/extract elements from the beginning of the list with unshift/shift', () => {
    const list = new LinkedList<number>()
    list.unshift(10)
    list.unshift(20)
    expect(list.shift()).toBe(20)
    expect(list.shift()).toBe(10)
  })

  xit('unshift/pop', () => {
    const list = new LinkedList<number>()
    list.unshift(10)
    list.unshift(20)
    expect(list.pop()).toBe(10)
    expect(list.pop()).toBe(20)
  })

  xit('example', () => {
    const list = new LinkedList<number>()
    list.push(10)
    list.push(20)
    expect(list.pop()).toBe(20)
    list.push(30)
    expect(list.shift()).toBe(10)
    list.unshift(40)
    list.push(50)
    expect(list.shift()).toBe(40)
    expect(list.pop()).toBe(50)
    expect(list.shift()).toBe(30)
  })

  xit('can count its elements', () => {
    const list = new LinkedList<number>()
    expect(list.count()).toBe(0)
    list.push(10)
    expect(list.count()).toBe(1)
    list.push(20)
    expect(list.count()).toBe(2)
  })

  xit('sets head/tail after popping last element', () => {
    const list = new LinkedList<number>()
    list.push(10)
    list.pop()
    list.unshift(20)
    expect(list.count()).toBe(1)
    expect(list.pop()).toBe(20)
  })

  xit('sets head/tail after shifting last element', () => {
    const list = new LinkedList<number>()
    list.unshift(10)
    list.shift()
    list.push(20)
    expect(list.count()).toBe(1)
    expect(list.shift()).toBe(20)
  })

  xit('deletes the element with the specified value from the list', () => {
    const list = new LinkedList<number>()
    list.push(10)
    list.push(20)
    list.push(30)
    list.delete(20)
    expect(list.count()).toBe(2)
    expect(list.pop()).toBe(30)
    expect(list.shift()).toBe(10)
  })

  xit('deletes the only element', () => {
    const list = new LinkedList<number>()
    list.push(10)
    list.delete(10)
    expect(list.count()).toBe(0)
  })

  xit('delete does not modify the list if the element is not found', () => {
    const list = new LinkedList<number>()
    list.push(10)
    list.delete(20)
    expect(list.count()).toBe(1)
  })
})
class LinkedList<T> {
  private tail?: Node<T>;
  private head?: Node<T>;
  private _count: number = 0;

  count(): number {
    return this._count;
  }

  push(val: T): void {
    if (this.count() === 0) {
      this.tail = this.head = new Node(val);
    } else if (this.tail) {
      const oldTail = this.tail;
      this.tail = new Node(val);
      this.tail.prev = oldTail;
      oldTail.next = this.tail;
    }
    this._count++;
  }

  pop(): T {
    if (this.tail) {
      const val = this.tail.val;
      this.tail = this.tail.prev;
      this._count--;
      return val;
    }
    throw new Error("No Nodes in the list");
  }

  shift(): T {
    if (this.head) {
      const val = this.head.val;
      this.head = this.head.next;
      this._count--;
      return val;
    }
    throw new Error("No Nodes in the list");
  }

  unshift(val: T): void {
    if (this.count() === 0) {
      this.head = this.tail = new Node(val);
    } else if (this.head) {
      const oldHead = this.head;
      this.head = new Node(val);
      this.head.next = oldHead;
      oldHead.prev = this.head;
    }
    this._count++;
  }

  delete(val: T): void {
    if (this.head) {
      if (this.head.val === val) {
        this.shift();
      } else {
        let cur = this.head.next;
        while (cur) {
          if (cur.val === val) {
            if (cur.prev && cur.next) {
              cur.prev.next = cur.next;
              cur.next.prev = cur.prev;
              this._count--;
              return;
            }
          } else {
            cur = cur.next;
          }
        }
      }
    }
  }
}

class Node<T> {
  next?: Node<T>;
  prev?: Node<T>;
  val: T;
  constructor(val: T) {
    this.val = val;
  }
}

export default LinkedList;

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?