Last active
July 20, 2018 20:45
-
-
Save DmytroVasin/e4e960d9f60c46ac0fb415f84193ba5d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Implement generic for two way linked list for different items type. | |
| interface ILinkedList<T> { | |
| append(value: T); | |
| pop():T|null; | |
| showlist():void; | |
| } | |
| class LinkedList<T> implements ILinkedList<T> { | |
| public head:MyNode<T> | |
| public tail:MyNode<T> | |
| public length:number | |
| constructor(){ | |
| this.head = null | |
| this.tail = null | |
| this.length = 0 | |
| } | |
| public append(value: T):MyNode<T> { | |
| let node = new MyNode<T>(value) | |
| this.head = this.head || node | |
| if (this.tail) { | |
| this.tail.next = node | |
| node.prev = this.tail | |
| } | |
| this.tail = node | |
| this.length += 1 | |
| return node | |
| } | |
| // Is it correct? | |
| public pop(): T|null { | |
| if (!this.head) { return null } | |
| let _tail = this._pop() | |
| if (!this.tail) { | |
| this.head = null | |
| } | |
| this.length -= 1 | |
| return _tail.value | |
| } | |
| public showlist():void { | |
| console.log('Length:', this.length) | |
| let _node = this.head | |
| while (_node) { | |
| console.log('Node Value:', _node.value) | |
| _node = _node.next | |
| } | |
| } | |
| private _pop():MyNode<T> { | |
| let _node = this.tail | |
| this.tail = this.tail.prev | |
| if (this.tail) { | |
| this.tail.next = null | |
| } | |
| return _node | |
| } | |
| } | |
| class MyNode<T> { | |
| public value = null | |
| public next = null | |
| public prev = null | |
| constructor(val: T){ | |
| this.value = val | |
| } | |
| } | |
| const ll = new LinkedList | |
| ll.append(10) | |
| ll.append('20') | |
| ll.append(30) | |
| ll.pop() | |
| ll.append('150') | |
| ll.append(200) | |
| ll.pop() | |
| ll.append({ hello: 'world' }) | |
| ll.append(function(){ let idle }) | |
| ll.append(NaN) | |
| ll.append(undefined) | |
| ll.append(40) | |
| ll.showlist() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment