Skip to content

Instantly share code, notes, and snippets.

@sigmasoldi3r
Created January 17, 2020 17:46
Show Gist options
  • Save sigmasoldi3r/d04fd973c2e69538b701985eedcd4e5e to your computer and use it in GitHub Desktop.
Save sigmasoldi3r/d04fd973c2e69538b701985eedcd4e5e to your computer and use it in GitHub Desktop.
A simple double-linked-list in typescript, with iteration included. This was a part of a project that was not needed at the end.
/*
Copyright Pablo Blanco Celdrán 2020
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
export type LLNode<T> = {
previous
: null
| LLNode<T>
next
: null
| LLNode<T>
value
: T
} ;;
/**
* Linked lists do not need to re-allocate each time they outgrow the internal
* array.
* This particular implementation is expensive tho, but yields a constant
* insertion time.
*/
export class LinkedList<T> implements Iterable<T> {
private tail: LLNode<T> | null;
private head: LLNode<T> | null;
private _length: number = 0;
public get length() {
return this._length;
}
/**
* Pushes the element at the end of the list.
*/
public push(value: T) {
if (this.length === 0) {
this.head = {
previous: null,
next: null,
value
};
this.tail = this.head;
} else {
this.head = {
previous: this.head,
next: null,
value
}
this.head.previous.next = this.head;
}
this._length++;
}
/**
* Pops the last element.
*/
public pop(): T | null {
if (this.length === 0) {
return null;
}
this._length--;
const value = this.head.value;
if (this.length === 0) {
this.head = this.tail = null;
}
this.head = this.head.previous;
return value;
}
*elements() {
for (let current = this.tail; current !== null;) {
yield current.value;
current = current.next;
}
}
[Symbol.iterator](): Iterator<T> {
return this.elements();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment