enh(single-link-list): added insert at the end method (#493)

pull/449/head^2
atulll 2021-09-29 00:14:39 +05:30 committed by GitHub
parent 5f88b6447a
commit 425005e751
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 20 additions and 0 deletions

View File

@ -32,6 +32,24 @@ class SinglyLinkedList {
return data; 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() { printList() {
// if head is null then list is empty // if head is null then list is empty
if (this.head == null) { if (this.head == null) {
@ -52,4 +70,6 @@ array.insertAtHead(1);
array.insertAtHead('xyz'); array.insertAtHead('xyz');
array.insertAtHead(1.1); array.insertAtHead(1.1);
array.removeAtHead(); array.removeAtHead();
array.insertAtEnd(99);
array.printList(); array.printList();