From e87e38b62b4f734bf42a5be48f06ca213a8ac49f Mon Sep 17 00:00:00 2001 From: oleksii golikov Date: Mon, 9 Jul 2018 21:36:34 +0300 Subject: [PATCH] single and doubly lists --- JavaScript/7-single.js | 64 ++++++++++++++++++++++++++++++++++++++++ JavaScript/8-doubly.js | 66 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 130 insertions(+) create mode 100644 JavaScript/7-single.js create mode 100644 JavaScript/8-doubly.js diff --git a/JavaScript/7-single.js b/JavaScript/7-single.js new file mode 100644 index 0000000..b01fef0 --- /dev/null +++ b/JavaScript/7-single.js @@ -0,0 +1,64 @@ + +const Node = (value, next = null) => ({ + value, + next, +}); + +const LinkedList = () => { + const list = { + head: null, + + append(value) { + if (!list.head) { + list.head = Node(value) + } else { + let node = list.head; + while (node.next) { + node = node.next; + } + node.next = Node(value); + } + }, + + remove(value) { + let prev = null; + let node = list.head; + + while (node) { + if (node.value === value) { + if (node === list.head) { + list.head = node.next; + } else { + prev.next = node.next; + } + } + prev = node; + node = node.next; + } + }, + + [Symbol.iterator]: function* () { + let node = list.head; + while (node) { + yield node.value; + node = node.next; + } + } + }; + return list; +}; + +// Usage + +const list = LinkedList(); + +list.append(1); +list.append(2); +list.append(3); +list.append(4); +list.remove(3); + +for (item of list) { + console.log(item); +} + diff --git a/JavaScript/8-doubly.js b/JavaScript/8-doubly.js new file mode 100644 index 0000000..b7db993 --- /dev/null +++ b/JavaScript/8-doubly.js @@ -0,0 +1,66 @@ + +const Node = (value, prev = null, next = null) => ({ + value, + prev, + next, +}); + +const DoublyLinkedList = () => { + const list = { + head: null, + + append(value) { + if (!list.head) { + list.head = Node(value) + } else { + let node = list.head; + while (node.next) { + node = node.next; + } + node.next = Node(value, node); + } + }, + + remove(value) { + let node = list.head; + + while (node) { + if (node.value === value) { + if (node === list.head) { + list.head = node.next; + } else { + node.prev.next = node.next; + if (node.next) { + node.next.prev = node.prev; + } + } + } + node = node.next; + } + }, + + [Symbol.iterator]: function* () { + let node = list.head; + while (node) { + yield node.value; + node = node.next; + } + } + }; + return list; +}; + +// Usage + +const list = DoublyLinkedList(); + +list.append(1); +list.append(2); +list.append(3); +list.append(4); +list.remove(3); + +for (item of list) { + console.log(item); +} +