From 425005e751c0c843d1274bd760978d124fc338a6 Mon Sep 17 00:00:00 2001 From: atulll <39869656+underager@users.noreply.github.com> Date: Wed, 29 Sep 2021 00:14:39 +0530 Subject: [PATCH] enh(single-link-list): added insert at the end method (#493) --- .../JavaScript/src/linked-lists/singly.js | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/algorithms/JavaScript/src/linked-lists/singly.js b/algorithms/JavaScript/src/linked-lists/singly.js index c770fd98..3a42dd71 100644 --- a/algorithms/JavaScript/src/linked-lists/singly.js +++ b/algorithms/JavaScript/src/linked-lists/singly.js @@ -32,6 +32,24 @@ class SinglyLinkedList { return data; } + insertAtEnd(data) { + const newNode = new Node(data); + if (!this.head) { + this.head = newNode; + return this; + } + + let currentNode = this.head; + + while (currentNode.next) { + currentNode = currentNode.next; + } + + currentNode.next = newNode; + + return this; + } + printList() { // if head is null then list is empty if (this.head == null) { @@ -52,4 +70,6 @@ array.insertAtHead(1); array.insertAtHead('xyz'); array.insertAtHead(1.1); array.removeAtHead(); +array.insertAtEnd(99); array.printList(); +